views:

41

answers:

1

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  A: 

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");
Quintin Robinson