views:

2170

answers:

1

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?

+4  A: 

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.

Mikko Rantanen
Answering my own question. XmlNameTable is used for optimizing string comparisons and I guess the reason you can give the XmlNamespaceManager an existing name table allows fast comparisons with the XmlDocument elements as these then share the NameTable.
Mikko Rantanen
Your update seems to make sense. I was trying to put up an abbreviated form of the xml, and forgot to post the namespace. Thank you for taking the extra time to try and figure this one out. Once I removed the namespace from the original xml, everything works out like it should. Definitely worth more study of the System.Xml namespace.
fauxtrot