XmlElement.SelectNodes (..) - does not find anything. Help?

Sorry to bother you with such a simple question, but I'm stuck here for 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 am trying to access ddd elements 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 run time, the foreach loop is skipped because I do not get any nodes from the .SelectNodes method. I broke through before the loop and looked at InnerXML, which looks great, and I also tried all kinds of XPaths (like "// bbb" or "/ aaa / ddd"), but only "/" does not seem to return zero.

This exact code worked for me before, now it is not. I suspect something with this namespace declaration in the aaa tag, but I could not understand why this should cause problems. Or ... can you see something that I might lose?

+6
source share
1 answer

This is the xml namespace. No ddd . However, there is x:ddd , where x is your alias http://blabla.com/xmlschema/v1 . You need to test the namespace - 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 case is arbitrary; in x there is no meaning other than convenience.

This (rather inconvenient) means adding a namespace (or an alias as above) to all of your xpath expressions.

+10
source

Source: https://habr.com/ru/post/900438/


All Articles