How to deserialize XML namespaces in C # (System.Xml.Serialization)?

I'm just finishing touches to my Zthes format deserializer (System.Xml.Serialization), which uses the “DC” namespace in the “thes” element. All the "term" elements are deserialized perfectly because they do not have a namespace, but I cannot figure out how to tell the deserializer that the "thes" elements have a namespace.

Here is what I am trying to do (which is not working), so hopefully someone can give me the correct syntax.

[XmlElement("namespace:someElement")]
public string SomeElement;
+5
source share
2 answers

Here is a quick example ...

[XmlRoot("myObject")]
public class MyObject
{
    [XmlElement("myProp", Namespace = "http://www.whited.us")]
    public string MyProp { get; set; }

    [XmlAttribute("myOther", Namespace = "http://www.whited.us")]
    public string MyOther { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var xnames = new XmlSerializerNamespaces();
        xnames.Add("w", "http://www.whited.us");
        var xser = new XmlSerializer(typeof(MyObject));
        using (var ms = new MemoryStream())
        {
            var myObj = new MyObject()
            {
                MyProp = "Hello",
                MyOther = "World"
            };
            xser.Serialize(ms, myObj, xnames);
            var res = Encoding.ASCII.GetString(ms.ToArray());
            /*
                <?xml version="1.0"?>
                <myObject xmlns:w="http://www.whited.us" w:myOther="World">
                  <w:myProp>Hello</w:myProp>
                </myObject>
             */
        }
    }
}
+8
source
[XmlElement("someElement", Namespace="namespace")]
public string SomeElement;

: , " " - URI , .

+1

All Articles