Home > Software engineering >  XML SelectSingleNode in xmlns default namespace which seems to have some other value in it
XML SelectSingleNode in xmlns default namespace which seems to have some other value in it

Time:05-20

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

I am trying to extract the value of ID element under Reference element using the following code and it SelectSingleNode call 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

CodePudding user response:

In order to find the node, you have to register the namespaces correctly, e.g.:

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");

Please note that both namespaces are registered with a name that is also used as a prefix in the query. If you run the query, the output is:

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