5

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;

2 Answers 2

8

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>
             */
        }
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

OP's question is about deserializing, not serializing. The deserialize method does not take a XmlSerializerNamespaces parameter.
I guess that is why they accepted my answer 6 years ago,
1
[XmlElement("someElement", Namespace="namespace")]
public string SomeElement;

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.