Cannot get .NET XPathNavigator to work

I'm having problems with XPathNavigator. I have a document with a bunch of "theme" elements with no namespace in the stream.

I use (an expression lowered to a minimum, at first I thought my expressions were wrong):

XPathDocument xmlDoc = new XPathDocument( stream );
XPathNavigator xml = xmlDoc.CreateNavigator();
XPathNodeIterator iter = xml.Select( "//topic" );

This does not work. I can choose */*/*or something similar and get my "themes" in order. I tried to use my expressions in an online test and other languages, and they work.

Question: what happened? My suspicion dragged on that this was due to the cursed NamespaceManager, which causes me incredible pain every time I parse a document with namespaces, but this time the elements I'm looking for don't have an explicit namespace! I added:

XmlNamespaceManager s = new XmlNamespaceManager( xml.NameTable ); 

and pass it as the 2nd argument for the choice - to no avail. How should I add a "" namespace to this thing / use it correctly?

Or, even better, is there a way to use XPath in .NET without using this terrible abomination of a class like in other languages? If I need namespaces, I can write them in an expression ...

Update: I figured out a workaround - copy / paste the default xmlns from the root node, and then use this namespace:

thisIsRetarded.AddNamespace( "x", "urn:xmind:xmap:xmlns:content:2.0" );
XPathNodeIterator projectIter = projectTree.Select( "//x:topic", thisIsRetarded );

however, I also do not need to know the default URI, and I do not like to pollute my expressions with unnecessary x: -s. Therefore, I now only need to answer the second part of the question.

+3
source share
1 answer

XmlDocument:

XmlDocument doc = new XmlDocument();
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("sample", "...");
doc.Load(stream);

XmlNode topic = doc.SelectSingleNode("/sample:topic", nsmgr);

// If you don't have any namespaces....
XmlNode topic2 = doc.SelectSingleNode("/topic"); 
+4

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


All Articles