简体   繁体   中英

How can I pull out the XML namespace prefix from an XElement object?

I have an XElement object pulled out of an XDocument object, for example

XDocument doc = XDocument.Parse(@"<billpg:MyRoot xmlns:billpg=""http://billpg.com/rutabaga"" />");
XElement elem = doc.Root; /* Or any element inside the document. */

How can I pull out the XML prefix from this XElement object?
(In the above example for elem is "billpg".)

I can get the full URL namespace from elem.Name.Namespace.NamespaceName , but I'm trying to pull out the short "billpg" part instead. I'll also note that elem.ToString() returns a string that includes "billpg" in the right place which could probably be regex'd out. While this would work, its not really in the spirit of using an XML library.

Use the GetPrefixOfNamespace() method to achieve this:

var prefix = elem.GetPrefixOfNamespace(elem.Name.Namespace);

More info on this you can find in the documentation: https://docs.microsoft.com/en-us/dotnet/api/system.xml.linq.xelement.getprefixofnamespace

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