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

This may be a duplicate, since my question seems so trivial, but I could not find the answer here on stackoverflow.com .

I have an XElement with the following data:

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

Question: How to get the full name with a string prefix from XElement?

Expected Result :

 abc:MyElement 
+6
source share
5 answers

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

Although this is not a good 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 :)

+8
source

That's right, I did not use the same objects as you. with LINQ namesapce you solve the following:

 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 
+2
source
 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> 
+1
source

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

0
source

This will return the prefix from XElement:

 myElement.GetPrefixOfNamespace(node.Name.Namespace); 
0
source

Source: https://habr.com/ru/post/890767/


All Articles