Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XmlElement.SelectNodes(..) - finds nothing.. Help?

Sorry to bother you with such a simple question, but I'm stuck here since an hour:

I have an xml file that looks something like this:

<?xml version="1.0" encoding="utf-8"?>
<aaa xmlns="http://blabla.com/xmlschema/v1">

  <bbb>
    <ccc>Foo</ccc>
  </bbb>

  <ddd x="y" />
  <ddd x="xx" />
  <ddd x="z" />

</aaa>

I'm trying to access the elements 'ddd' like this:

var doc = new XmlDocument();
doc.Load("example.xml");
foreach (XmlNode dddNode in doc.DocumentElement.SelectNodes("//ddd"))
{
   // do something
   Console.WriteLine(dddNode.Attributes["x"].Value);
}

At runtime the foreach loop is skipped because I don't get any nodes back from the .SelectNodes method. I breaked before the loop and had a look at the InnerXML, that looks fine, and I also tried all sorts of XPaths (like "//bbb" or "/aaa/ddd"), but only "/" seems to not return null.

This exact code worked for me before, now it does not. I suspect something with that namespace declaration in the aaa tag, but I couldn't figure out why this should cause problems. Or.. can you see anything I may be missing?

like image 343
Efrain Avatar asked Oct 31 '11 13:10

Efrain


1 Answers

This is xml-namespaces. There is no ddd. There is, however, x:ddd where x is your alias to http://blabla.com/xmlschema/v1. You'll need to test with namespaces - for example:

var nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("x", "http://blabla.com/xmlschema/v1");
var nodes = doc.DocumentElement.SelectNodes("//x:ddd", nsmgr);
// nodes has 3 nodes

Note x in the above is arbitrary; there is no significance in x other than convenience.

This (rather inconveniently) means adding the namespace (or an alias, as above) into all of your xpath expressions.

like image 125
Marc Gravell Avatar answered Sep 28 '22 09:09

Marc Gravell