How to have an attribute on an element of type string

天大地大妈咪最大 提交于 2019-12-14 02:33:45

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!