简体   繁体   中英

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

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");

I know this is an old topic, but I had the same problem, using the XmlDocument class, as I wanted to know the Default Namespace and a prefixed 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 on a XmlElement.

Edit: This is a XmlNode Method, so should also work on Attributes

The simplest way to do it

XmlDocument xDoc = new XmlDocument();
xDoc.Load(uriPath);
Console.WriteLine(xDoc.NamespaceURI);

You could try using XmlNamespaceManager.DefaultNamespace to get it.

http://msdn.microsoft.com/en-us/library/system.xml.xmlnamespacemanager.defaultnamespace.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM