【问题标题】:How to deserialize xml with xmlns?如何使用 xmlns 反序列化 xml?
【发布时间】:2015-08-19 21:46:47
【问题描述】:

你用 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 类

[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>

【问题讨论】:

    标签: c# xml xml-deserialization


    【解决方案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")]
    

    【讨论】:

    • 谢谢,这行得通。但是,我将 XmlRootAttribute 与 Namespace 属性一起使用,并删除了 nzb 类属性。
    猜你喜欢
    • 2012-04-28
    • 1970-01-01
    • 2018-08-28
    • 2011-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-23
    • 2010-12-06
    相关资源
    最近更新 更多