Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am just putting the finishing touches to my Zthes format deserializer (System.Xml.Serialization) which uses the namespace "dc" in the element "thes". All "term" elements are deserializing fine because they have no 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 isn't working) so hopefully someone could give me the proper syntax.

[XmlElement("namespace:someElement")]
public string SomeElement;
like image 646
Ryall Avatar asked Oct 09 '09 16:10

Ryall


People also ask

What is the correct way of using XML Deserialization?

To deserialize the objects, call the Deserialize method with the FileStream as an argument. The deserialized object must be cast to an object variable of type PurchaseOrder . The code then reads the values of the deserialized PurchaseOrder .

What is a namespace for XML serialization?

Xml. Serialization namespace contains several Attribute classes that can be applied to members of a class. For example, if a class contains a member that will be serialized as an XML element, you can apply the XmlElementAttribute attribute to the member.


2 Answers

Here's a quick sample for you...

[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>
             */
        }
    }
}
like image 167
Matthew Whited Avatar answered Sep 24 '22 14:09

Matthew Whited


[XmlElement("someElement", Namespace="namespace")]
public string SomeElement;

Addendum: Make sure "namespace" is the full URI of the namespace, not just the prefix.

like image 35
Eric Rosenberger Avatar answered Sep 25 '22 14:09

Eric Rosenberger