When I want to traverse my XmlDocument using XPath, I came unto the problem that there were many ugly namespaces in the document, so I started using a NamespaceManager
along with the XPath.
The XML looks like this
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:html="http://www.w3.org/TR/REC-html40">
<Worksheet ss:Name="KA0100401">
<Table>
<Row>
<Cell>Data</Cell>
</Row>
<!-- more rows... -->
</Table>
</Worksheet>
<Worksheet ss:Name="KA0100402">
<!-- .... --->
</Worksheet>
</Workbook>
Now, from what I see from this document, "urn:schemas-microsoft-com:office:spreadsheet"
is the default namespace, because it sits on the root element.
So, naively, I configured my NamespaceManager
like this:
XmlDocument document = new XmlDocument();
document.Load(reader);
XmlNamespaceManager manager = new XmlNamespaceManager(document.NameTable);
manager.AddNamespace(String.Empty, "urn:schemas-microsoft-com:office:spreadsheet");
manager.AddNamespace("o", "urn:schemas-microsoft-com:office:office");
manager.AddNamespace("x", "urn:schemas-microsoft-com:office:excel");
manager.AddNamespace("ss", "urn:schemas-microsoft-com:office:spreadsheet");
manager.AddNamespace("html", "http://www.w3.org/TR/REC-html40");
But, when I try to access a node
foreach (XmlNode row in document.SelectNodes("/Workbook/Worksheet[1]/Table/Row", manager))
I never get any results. I was under the impression that by setting the first namespace with an empty prefix, I wouldn't need to set that when searching for nodes in that workspace.
But, as it is stated on the AddNamespace
method:
If an XPath expression does not include a prefix, it is assumed that the namespace Uniform Resource Identifier (URI) is the empty namespace.
Why is that? And, more important: How do I access nodes in the default namespace, if not using a prefix sets them into an empty namespace?
What good is setting the default namespace on the manager if I can't even access it when searching for nodes?