【问题标题】:Reading XML fails when the parent node has XMLNS父节点有 XMLNS 时读取 XML 失败
【发布时间】:2013-12-24 08:04:55
【问题描述】:

我有一个读取 xml 信息的应用程序。 它工作正常,但是当我的父节点添加了 XMLNS 时,它停止工作并开始抛出 Null 引用异常。

这应该是什么可能的解决方案

XML 文件

<Info  xmlns="urn:smilu.com">
  <Number>123456</Number>  
  <Gender>2</Gender>
  <NamesEng>
    <First>FirstName</First>
    <Second>SecondName</Second>
    <Third>ThirdName</Third>
    <Fourth>FourthName</Fourth>
    <Fifth>FifthName</Fifth>
    <Sixth>SixthName</Sixth>
  </NamesEng> 
</Info>

我的 C# 阅读代码是

 NameTable nt = new NameTable();
XmlNamespaceManager nsMgr = new XmlNamespaceManager(nt);                
nsMgr.AddNamespace("ns", "urn:smilu.com");

XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(_LabourXMLInfo);

string Number = xdoc.DocumentElement.SelectSingleNode("Number", nsMgr).InnerText;

如果我从 Info 节点中删除 xmlns,上述代码将完美运行。但是,添加了 xmlns 后,我发现异常。 请帮我解决这个问题。

【问题讨论】:

  • 我试过但没用
  • 我解决了这个问题。 XmlNamespaceManager nsMgr = new XmlNamespaceManager(xdoc.NameTable);并在所有代码中保留 ns: 作为前缀

标签: c# asp.net xml xmldocument


【解决方案1】:

您正在声明 XML 命名空间 - 但您实际上并没有使用它(引用它)。

将您的代码更改为:

XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(_LabourXMLInfo);

// define XML namespace manager based on the XmlDocument's NameTable
XmlNamespaceManager nsMgr = new XmlNamespaceManager(xdoc.NameTable);
nsMgr.AddNamespace("ns", "urn:smilu.com");

// add a "ns:" prefix to the XPath expression here!
string Number = xdoc.DocumentElement.SelectSingleNode("ns:Number", nsMgr).InnerText;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-11
    相关资源
    最近更新 更多