Can't Get .NET XPathNavigator to work

.net, c#, xpath, xpathnavigator

Solution

I prefer to use `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"); 

Problem

I am having problems with XPathNavigator. I have a document with a bunch of "topic" elements w/o namespace in a stream. I am using (expression dumbed down to bare minimum, first I thought my expressions were wrong): ``` XPathDocument xmlDoc = new XPathDocument( stream ); XPathNavigator xml = xmlDoc.CreateNavigator(); XPathNodeIterator iter = xml.Select( "//topic" ); ``` This doesn't work. I can select `*/*/*` or something similar and get my "topic" elements alright. I tried running my expressions in online tester and other languages and they work. Question: what's wrong? I have lingering suspicion that it has to do with accursed NamespaceManager object, which causes me incredible pain every time I parse document with namespaces, but this time the elements I am seeking don't have an explicit namespace! I added: ``` XmlNamespaceManager s = new XmlNamespaceManager( xml.NameTable ); ``` and pass that as 2nd argument to Select - to no avail. How am I supposed to add "" namespace to this thing/use it correctly? Or, better yet, is there way to use XPath in .NET without using this horrible abomination of the class, like in other languages? If I want namespaces, I can write them in the expression... Update: I figured out a workaround- copy/paste default xmlns from root node, and then use that namespace: ``` thisIsRetarded.AddNamespace( "x", "urn:xmind:xmap:xmlns:content:2.0" ); XPathNodeIterator projectIter = projectTree.Select( "//x:topic", thisIsRetarded ); ``` however, neither I am supposed to know the default URI, nor do I like to pollute my expressions with unnecessary x:-s. So I only need answer to 2nd part of the question now.

Original source

Related problems