Cœur
Cœur

Reputation: 38727

DataContractSerializer to deserialize a Member without namespace?

I need to deserialize this xml (that I can't change):

<foo:a xmlns:foo="http://example.com">
  <b>string</b>
</foo:a>

I made this class:

[DataContract(Name = "a", Namespace = "http://example.com")]
public class A
{
    [DataMember(Name = "b", Order = 0)]
    public string B;
}

And I did:

using (var streamObject = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
{
    var ser = new DataContractSerializer(typeof(A));
    return (A)ser.ReadObject(streamObject);
}

I get an object of class A, but the content of B is always null. I know it would work if the xml was using <foo:b>string</foo:b>, but that is not the case. What can I do to deserialize a DataMember with no namespace?

Upvotes: 2

Views: 6317

Answers (1)

Andrew
Andrew

Reputation: 3806

if you can do the pre-processing of xml before deserializing it, then try to do the following:

make namespace in your datacontract empty:

[DataContract(Name = "a", Namespace = "")]
public class A
{
    [DataMember(Name = "b", Order = 0)]
    public string B;
}

remove the namespace attribute from your xml before deserializing it

XDocument doc = XDocument.Parse("your xml here");
XElement root = doc.Root;

XAttribute attr = root.Attribute("xmlns");
if (attr != null) 
{
    attr.Remove();
}

and then deserialize the updated xml:

string newXml = doc.ToString();   

A result = null;
DataContractSerializer serializer = new DataContractSerializer(typeof(A));

using (StringReader backing = new StringReader(newXml))
{
    using (XmlTextReader reader = new XmlTextReader(backing))
    {
        result = (A) serializer.ReadObject(reader);
    }
}

Upvotes: 2

Related Questions