开发者

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

开发者 https://www.devze.com 2022-12-07 18:31 出处:网络
This might be duplicate since my question seems so trivial, but I haven\'t been able to find the answer here on stackoverflow.com.

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:MyElemen开发者_开发技巧t>

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

Expected result:

abc:MyElement


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


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


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


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>


This will return prefix from XElement:

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

精彩评论

暂无评论...
验证码 换一张
取 消