问题
If I have
[XmlElement(ElementName = "Title")]
public string Title;
How can i include an attribute in title without declaring a class (its type is just a string)?? so that when i serialize using XML serializer, the output is something like this:
<Movie>
<Title x:uid="movie_001">Armagedon</Title>
<Date>010101</Date>
<Movie>
and not like this:
<Movie>
<Title x:uid="movie_001" MovieTile="Armagedon"\>
<Date>010101</Date>
<Movie>
回答1:
I don't think this is possible without having Title be a custom type or explicitly implementing serialization methods.
You could do a custom class like so..
class MovieTitle
{
[XmlText]
public string Title { get; set; }
[XmlAttribute(Namespace="http://www.myxmlnamespace.com")]
public string uid { get; set; }
public override ToString() { return Title; }
}
[XmlElement(ElementName = "Title")]
public MovieTitle Title;
which should produce:
<Title x:uid="movie_001">Armagedon</Title>
Although the serializer can do interesting things with unknown namespaces.
You can avoid the wierd behaviour by declaring your namespaces and providing the object to the serializer..
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("x", "http://www.myxmlnamespace.com");
来源:https://stackoverflow.com/questions/692147/how-to-have-an-attribute-on-an-element-of-type-string