views:

73

answers:

2

If i have a class MovieClass as

[XmlRoot("MovieClass")]
public class Movie
{
   [XmlElement("Novie")]
   public string Title;

   [XmlElement("Rating")]
   public int rating; 
}

How can I have an attribute "x:uid" in my "Movie" element, so that the output when XmlSerializer XmlSerializer s = new XmlSerializer(typeof(MovieClass)) was used is like this:

<?xml version="1.0" encoding="utf-16"?>
<MovieClass>
   <Movie x:uid="123">Armagedon</Movie>
</MovieClass>

and not like this

<?xml version="1.0" encoding="utf-16"?>
<MovieClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;
   <Movie x:uid="123" Title="Armagedon"/>
</MovieClass>

Note: I want the xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" removed, if possible.

+2  A: 

I answered this in your original post, but I think this one is worded better so I will post it here as well, if it gets closed as duplicate you can modify your original post to mirror this question.

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; }
}

[XmlRoot("MovieClass")]
public class Movie
{
   [XmlElement("Movie")]
   public MovieTitle Title;
}

which will produce:

<MovieClass xmlns:x="http://www.myxmlnamespace.com"&gt;
  <Movie x:uid="movie_001">Armagedon</Movie>
</MovieClass>

Although the serializer will compensate for unknown namespaces with a result you probably won't expect.

You can avoid the wierd behavior by declaring your namespaces and providing the object to the serializer..

  XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
  ns.Add("x", "http://www.myxmlnamespace.com");
Quintin Robinson
A: 

It's not valid XML if you don't have x declared as a namespace prefix. Quintin's response tells you how to get valid XML.

Cheeso