XML SelectNode() returns nothing. Why does namespace matter?

c#, xml

Solution

<SessionStateInfo ....
    xmlns="http://schemas.datacontract.org/2004/07/MoreHere.Session">

means that this element and all its descendants are in the `http://schemas.datacontract.org/2004/07/MoreHere.Session` namespace. Since unprefixed names in an XPath always refer to elements in no namespace, you will need to bind this URI to a prefix and use that prefix in your XPath, even though no prefix is in use in the document.

XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("mhs", "http://schemas.datacontract.org/2004/07/MoreHere.Session");
xmlNodes = rootElement.SelectNodes("mhs:DefinitionName", nsmgr);

If you know that the element(s) you are looking for will always have the same local name but may or may not have a namespace (or may have different namespaces) then you can use XPath tricks like

rootElement.SelectNodes("*[local-name() = 'DefinitionName']");

Problem

I have code to get the nodes of a root element: ``` xmlNodes = rootElement.SelectNodes("DefinitionName"); ``` It's not returning nodes that exist. In the debugger, I can expand rootElement to find DefinitionName. Apparently the problem is the fact that the file has a namespace defined (see XML below). MSDN says that I have to do something like this to get nodes to return: Note: This has nothing to do with my code. This is the example from MSDN: ``` XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable); nsmgr.AddNamespace("ab", "http://www.lucernepublishing.com"); XmlNodeList nodelist = doc.SelectNodes("//ab:book", nsmgr); ``` I have two questions: - Why does the namespace matter? If I want a node, and it exists, just give it to me. - My app processes many XML files. How am I supposed to specify the namespace (`nsmgr.AddNamespace()`)? Do I need to parse the file to get that first? I can't help but feeling that I'm taking the long, angst-filled way of doing this. This is the XML: ``` <?xml version="1.0" encoding="utf-8"?> <SessionStateInfo xmlns:i="http://www.w3.org/2001/XMLSchema-instance" z:Id="1" z:Type="Company.Apps.MoreHere.Session.SessionStateInfo" z:Assembly="assembly info here" xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/" xmlns="http://schemas.datacontract.org/2004/07/MoreHere.Session"> <CoaterNumber>25</CoaterNumber> <DefinitionName z:Id="2">Two Line</DefinitionName> <EnableManualMode>true</EnableManualMode> ```

Original source