Why is SelectSingleNode returning null?

2019-01-19 04:57发布

问题:

I'm working with an XML document that contains a structure that looks similar to this:

<MT>
  <Events>
    <event id="1">
      <field name="blah" value="a_value" type="atype" />
      .
      .
      .
     </event>
   </Events>
 </MT>

I'm currently loading this from a file into an XML document in this fashion:

XmlDocument xdoc = new XmlDocument();
xdoc.Load("somefile.xml");  //Successfully loads btw

However I'm running into a problem and only with this one particular document when I try to run the next line of code:

xdoc.SelectSingleNode("//event[@id='1']"); //This returns a null 

Am I on the right track by guessing that this is returning null because of an issue with using an attribute named 'id' or am I missing something in code?

回答1:

I cannot replicate this using an XML file

<MT>
  <Events>
    <event id="1">
      <field name="blah" value="a_value" type="atype" />
     </event>
   </Events>
</MT>

And code

XmlDocument doc = new XmlDocument();
doc.Load(@"C:\test.xml");

XmlNode node = doc.SelectSingleNode("//event[@id='1']");

This returns a non-null node as expected.

Update

After adding a xmlns="example.org" to the <MT> element, I had to configure a namespace manager for the XPath and use the namespace for the event. Couldn't get the default namespace to work for some reason.

XmlDocument doc = new XmlDocument();
doc.Load(@"D:\test.xml");

XmlNamespaceManager manager = new XmlNamespaceManager(doc.NameTable);
manager.AddNamespace("e", "http://example.org");

XmlNode node = doc.SelectSingleNode("//e:event[@id='1']", manager);

One thing confused me when trying to get this to work. Why does XmlNamespaceManager need XmlNameTable from the document if not for finding out what namespaces it contains? As in, why do I need to define the NameTable and the namespace? I'd appreciate if someone who knows could drop a short comment.