Reputation: 4728
I have some XML files to parse, some of them are like this:
<?xml version="1.0" encoding="UTF-8"?>
<ab:rootNode xmlns:ab="http://www.uri.com">
<ab:nodeDate>...</ab:nodeDate>
</ab:rootNode>
and other of them are without namespace:
<?xml version="1.0" encoding="UTF-8"?>
<rootNode>
<nodeDate>...</nodeDate>
</node>
In LINQ to XML, I should to precise the namespace otherwise it don't fine any nodes.
How to manage namespaces? Do I test if xmlns:ab="http://www.uri.com"
exist in the rootNode
element? and if it exists I create a XNamespace
and add it to the name element like this (pseudo code):
XNamespace ab = "http://www.uri.com";
string prefixe = String.Empty;
if (XmlNamespaceExists(ab , "rootNode")
{
prefixe = ab;
}
Upvotes: 1
Views: 94
Reputation: 1499860
You could use:
XNamespace ns = doc.Root.Name.Namespace;
var dates = doc.Descendants(ns + "nodeDate");
I believe that should work whether or not namespaces are used - it just ends up finding every nodeDate
element with the same namespace as the root element.
Upvotes: 2