![](/img/trans.png)
[英]How can I get rid of the namespace prefix from XElement like this (C#)?
[英]C#: How to get the name (with prefix) from XElement as string?
這可能是重復的,因為我的問題似乎微不足道,但我無法在stackoverflow.com上找到答案。
我有一個XElement ,其數據如下:
<abc:MyElement>My value</abc:MyElement>
問題:如何從XElement獲取帶有前綴的完整名稱作為字符串?
預期結果 :
abc:MyElement
到目前為止,我的解決方案是使用XElement
可用的方法GetPrefixOfNamespace
。
雖然不是一個漂亮的解決方案,它給了我我想要的東西:
XElement xml = new XElement(...);
string nameWithPrefix = xml.GetPrefixOfNamespace(xml.Name.Namespace) +
":" +
xml.Name.LocalName;
更優雅的解決方案非常受歡迎:)
正確我沒有使用與你相同的物體。 使用LINQ名稱,解決方案是:
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);
版畫
abc:MyElement
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);
版畫
<abc:MyElement xmlns:abc="http://foo.com">MyValue</abc:MyElement>
這將從XElement返回前綴:
myElement.GetPrefixOfNamespace(node.Name.Namespace);
string.Format("{0}:{1}", XElement.Prefix, XElement.Name)
不起作用嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.