我正在尝试反序列化以下xml
<?xml version="1.0" encoding="utf-8"?>
<ns2:myroot xmlns:ns2="http://jeson.com/">
<item>
<name>uno</name>
<price>1.25</price>
</item>
<item>
<name>dos</name>
<price>2.30</price>
</item>
</ns2:myroot>
使用这些类
public class item
{
[XmlElement(Namespace="")]
public string name { get; set; }
[XmlElement(Namespace = "")]
public double price { get; set; }
}
[XmlRoot("myroot", Namespace="http://jeson.com/")] //This was http://jeson.com, no slash at the end.
public class myrootNS
{
[XmlElement(Namespace = "")]
public item[] item { get; set; }
}
使用此方法
XmlSerializer serializer = new XmlSerializer(typeof(T), "http://jeson.com/");
XmlReaderSettings settings = new XmlReaderSettings();
using (StringReader textReader = new StringReader(xml))
{
using (XmlReader xmlReader = XmlReader.Create(textReader, settings))
{
return (T)serializer.Deserialize(xmlReader);
}
}
但不知怎的,我不断收到这个错误。
System.InvalidOperationException: There is an error in XML document (2, 2). --->
System.InvalidOperationException: <myroot xmlns='http://jeson.com/'> was not expected.
这样做的正确方法是什么?该方法适用于没有命名空间的反序列化。
答案 0 :(得分:9)
问题是myrootNS类的命名空间不正确,因为它与XML中的预期命名空间不匹配。
[XmlRoot("myroot", Namespace = "http://jeson.com/")]
public class myrootNS
{
[XmlElement(Namespace = "")]
public item[] item { get; set; }
}
请注意,Namespace
属性值的尾随 / 。这是我的反序列化方法:
static T Deserialize<T>(string xml)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
XmlReaderSettings settings = new XmlReaderSettings();
using (StringReader textReader = new StringReader(xml))
{
using (XmlReader xmlReader = XmlReader.Create(textReader, settings))
{
return (T)serializer.Deserialize(xmlReader);
}
}
}
答案 1 :(得分:3)
作为XmlRoot
属性的替代方法,您还可以使用备用XmlRootAttribute
constructor of XmlSerializer
来覆盖元素名称或命名空间不同的时间:
var serializer = new XmlSerializer(typeof(myrootNS),
new XmlRootAttribute
{
ElementName = "myroot",
Namespace = "http://jeson.com/"
});