Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

xml

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?

like image 416
James James Avatar asked Oct 20 '11 08:10

James James


2 Answers

var doc = XDocument.Parse(myXml);
XNamespace ns = doc.Root.GetDefaultNamespace();
like image 123
Muhammad Hasan Khan Avatar answered Oct 11 '22 12:10

Muhammad Hasan Khan


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");
like image 34
username Avatar answered Oct 11 '22 14:10

username