Chau
Chau

Reputation: 5570

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

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

Upvotes: 6

Views: 8200

Answers (5)

Khalil
Khalil

Reputation: 139

This will return prefix from XElement:

myElement.GetPrefixOfNamespace(node.Name.Namespace);

Upvotes: -1

Rob
Rob

Reputation: 2656

Correct I was not using the same objects as you. with LINQ namesapce you the solution is:

using System.Xml.XPath; // <-- Add this namespace.

XNamespace ci = "http://foo.com";
XElement root = new XElement(ci + "Root", new XAttribute(XNamespace.Xmlns + "abc", "http://foo.com"));
XElement childElement = new XElement(ci + "MyElement", "content");
root.Add(childElement);
var str = childElement.XPathEvaluate("name()"); // <-- Tell Xpath to do the work for you :).
Console.WriteLine(str);

prints

abc:MyElement

Upvotes: 3

Chau
Chau

Reputation: 5570

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 :)

Upvotes: 10

Bala R
Bala R

Reputation: 108957

XNamespace ci = "http://foo.com";
XElement myElement = new XElement(ci + "MyElement", "MyValue");
XElement rootElement = new XElement("root",
        new XAttribute(XNamespace.Xmlns + "abc", ci), myElement);

var str = myElement.ToString();
Console.WriteLine(str);

prints

<abc:MyElement xmlns:abc="http://foo.com">MyValue</abc:MyElement>

Upvotes: 0

therealmitchconnors
therealmitchconnors

Reputation: 2760

Does string.Format("{0}:{1}", XElement.Prefix, XElement.Name) not work?

Upvotes: 0

Related Questions