问题描述
我需要反序列化此xml(无法更改):
I need to deserialize this xml (that I can't change):
<foo:a xmlns:foo="http://example.com">
<b>string</b>
</foo:a>
我上了这堂课:
[DataContract(Name = "a", Namespace = "http://example.com")]
public class A
{
[DataMember(Name = "b", Order = 0)]
public string B;
}
我做到了:
using (var streamObject = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
{
var ser = new DataContractSerializer(typeof(A));
return (A)ser.ReadObject(streamObject);
}
我得到一个类A的对象,但是B的内容始终为null.我知道如果xml使用<foo:b>string</foo:b>
它将起作用,但是事实并非如此.我该怎么办才能反序列化没有名称空间的DataMember?
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?
推荐答案
如果可以在反序列化XML之前对其进行预处理,则尝试执行以下操作:
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;
}
在反序列化之前从XML中删除名称空间属性
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();
}
,然后反序列化更新的xml:
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);
}
}
这篇关于DataContractSerializer可以反序列化没有名称空间的Member?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!