How do I read/parse an XML document where the XML namespace alias is unknown?
The structure and namespaces of the XML document are known, but the alias is not. E.g.
<?xml version="1.0" encoding="utf-8"?>
<Order xmlns:aa="urn:namespace1"
xmlns:bb="urn:namespace2">
<aa:Quantity>1</aa:Quantity>
<bb:Price>9.98</bb:Price>
</Order>
Or
<?xml version="1.0" encoding="utf-8"?>
<Order xmlns:cc="urn:namespace1"
xmlns:dd="urn:namespace2">
<cc:Quantity>1</cc:Quantity>
<dd:Price>9.98</dd:Price>
</Order>
Update: I don’t know the XML namespace aliases up front. They can be whatever.
I need to supply the XmlNamespaceManager with a list of namespaces and alias with the AddNameSpace method like so:
XPathDocument xDoc = new XPathDocument(“Path to my file”);
XPathNavigator xNav = xDoc.CreateNavigator();
XmlNamespaceManager xmlns = new XmlNamespaceManager(xNav.NameTable);
xmlns.AddNamespace("aa", "urn:namespace1");
xmlns.AddNamespace("bb", "urn:namespace2");
But this is not XML namespace agnostics. My second document uses cc and dd as alias for the same namespace.
The code you have provided is namespace agnostic in the sense that the namespace prefixes used in the source XML does not matter. Given the namespace definitions in your question you have to use the prefixes defined by you in the XPATH, e.g. you have to use
aaandbb.However, this code will still successfully select from the XML where prefixes
ccandddare used as long as the namespacesurn:namespace1andurn:namespace2are correctly used.To be able to include namespace prefixes in the XPATH you have to use the overloads that accepts an
IXmlNamespaceResolver.To reiterate: When you define a namespace using the following code
You state that in your code (e.g. in the XPATH you intend to use) you will be using namespace prefix
aafor namespaceurn:namespace1.In the XML you want to parse you assign namespaces using an attribute:
It is important that the string
urn:namespace1matches both places to use that particular namespace. The prefixes are local to your code and the XML file respectively and they do not have to match.