DataContractSerializer to deserialize a Member without namespace?

会有一股神秘感。 提交于 2019-12-11 02:17:16

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/23154798/datacontractserializer-to-deserialize-a-member-without-namespace

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!