XML xmlns 默认命名空间中的 SelectSingleNode,其中似乎还有一些其他值

XML SelectSingleNode in xmlns default namespace which seems to have some other value in it

<?xml version="1.0" encoding="UTF-8"?>
<MyRootElement xmlns="urn:MyNamespaceUri_1">
  <Color>
    <Name>Primary</Name>
    <ID>1</ID>
    <Description>Red</Description>    
    <Status>In Use</Status>    
    <Reference xmlns="urn:MyNamespaceUri_2">
      <ColorCode>3</ColorCode>      
      <ID>1616</ID>
    </Reference>
  </Color>
</MyRootElement>

我正在尝试使用以下代码提取 Reference 元素下 ID 元素的值,它调用 SelectSingleNode returns null

XmlNamespaceManager nsmgr = new XmlNamespaceManager(myXmlDoc.NameTable);
nsmgr.AddNamespace(String.Empty, "urn:MyNamespaceUri_1");

XmlNode idXml = myXmlDoc.SelectSingleNode("/MyRootElement/Color/Reference/ID", nsmgr);
var colorIdValue = idXml.InnerText;

.Net fiddle, https://dotnetfiddle.net/BA1AYu

为了找到节点,您必须正确注册命名空间,例如:

XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
nsmgr.AddNamespace("ns1", "urn:MyNamespaceUri_1");
nsmgr.AddNamespace("ns2", "urn:MyNamespaceUri_2");

XmlNode idXml = xmlDoc.SelectSingleNode("/ns1:MyRootElement/ns1:Color/ns2:Reference/ns2:ID", nsmgr);

if (idXml != null)
    Console.WriteLine(idXml.OuterXml);
else
    Console.WriteLine("NOT FOUND");

请注意,这两个命名空间都使用一个名称注册,该名称也用作查询中的前缀。如果你运行查询,输出是:

<ID xmlns="urn:MyNamespaceUri_2">1616</ID>