Some other questions have asked how to use Xpath to query XML documents with a default namespace. The answer is to use a namespace manager to create an alias for the default namespace, and use that alias in your xpaths.
However, what if you don't know the URI of the default namespace in advance? How do you find it out from the XML document?
var doc = XDocument.Parse(myXml);
XNamespace ns = doc.Root.GetDefaultNamespace();
If you are using XmlDocument, you can get the default namespace by checking NamespaceURI of the root element:
var document = new XmlDocument();
document.LoadXml("<root xmlns='http://java.sun.com/xml/ns/j2ee'></root>");
var defaultNamespace = document.DocumentElement.NamespaceURI;
Assert.IsTrue(defaultNamespace == "http://java.sun.com/xml/ns/j2ee");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With