你用xmlns反序列化xml吗?下面是包含xmlns属性的简化xml,它无法使用下面的代码反序列化。我不断得到的内在异常是:
{"<nzb xmlns='http://www.nzb.com'> was not expected."}
代码
TextReader tr = new StreamReader("nzb.xml");
XmlReaderSettings settings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Ignore };
XmlReader xmlReader = XmlReader.Create(tr, settings);
XmlRootAttribute xRoot = new XmlRootAttribute();
xRoot.ElementName = "nzb";
xRoot.IsNullable = true;
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Nzb), xRoot);
Nzb nzbFile = (Nzb)xmlSerializer.Deserialize(xmlReader);
xmlReader.Close();
Nzb Class
[XmlRoot("nzb", Namespace = "urn:http://www.nzb.com")]
public class Nzb
{
}
nzb.xml
<?xml version="1.0" encoding="iso-8859-1" ?>
<!DOCTYPE nzb>
<nzb xmlns="http://www.nzb.com">
</nzb>
答案 0 :(得分:1)
您的XML根属性覆盖导致XmlSerialiser中的问题。这已在类Nzb的XmlRoot属性中定义。所以以下内容将起作用:
XmlReader xmlReader = XmlReader.Create(tr, settings);
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Nzb));
Nzb nzbFile = (Nzb)xmlSerializer.Deserialize(xmlReader);
xmlReader.Close();
但是,您需要将Nzb XMLRoot属性的名称空间更改为:
[XmlRoot("nzb", Namespace = "http://www.nzb.com")]