Find out the default namespace URI from an XML document in C #

Some other questions ask how to use Xpath to query XML documents with a default namespace. The answer is to use the namespace manager to create an alias for the default namespace and use that alias in your xpaths.

However, what if you do not know the default namespace URI in advance? How did you find out from the XML document?

+5
source share
4 answers
var doc = XDocument.Parse(myXml);
XNamespace ns = doc.Root.GetDefaultNamespace();
+11
source

If you are using an XmlDocument, you can get the default namespace by checking the 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");
+3

I know this is an old topic, but I had the same problem using the XmlDocument class, because I wanted to know the default namespace and the prefix namespace.

I could get both namespaces using the same method.

string prefixns = element.GetNamespaceOfPrefix("prefix");
string defaultns = element.GetNamespaceOfPrefix("");

this seems to work for me, getting both namespaces in an XmlElement.

Edit: this is an XmlNode method, so it should also work with attributes

0
source

All Articles