C#: How to get the name (with prefix) from XElement as string?

Chau picture Chau · Jun 17, 2011 · Viewed 7.2k times · Source

This might be duplicate since my question seems so trivial, but I haven't been able to find the answer here on stackoverflow.com.

I have an XElement with data like this:

<abc:MyElement>My value</abc:MyElement>

Question: How do I get the complete name with prefix as a string from the XElement?

Expected result:

abc:MyElement

Answer

Chau picture Chau · Jun 21, 2011

My solution so far has been to use the method GetPrefixOfNamespace available in the XElement.

Though not a pretty solution, it gives me what I want:

XElement xml = new XElement(...);
string nameWithPrefix = xml.GetPrefixOfNamespace(xml.Name.Namespace) + 
                        ":" + 
                        xml.Name.LocalName;

More elegant solutions are very welcome :)