Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
499 views
Welcome To Ask or Share your Answers For Others

1 Answer

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:est.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:est.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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...