![](/img/trans.png)
[英]How can I pull out the XML namespace prefix from an XElement object?
[英]How can I write xml with a namespace and prefix with XElement?
這可能是一個初學者xml問題,但是如何生成如下所示的xml文檔呢?
<root xmlns:ci="http://somewhere.com" xmlns:ca="http://somewhereelse.com">
<ci:field1>test</ci:field1>
<ca:field2>another test</ca:field2>
</root>
如果我可以寫這個,我可以解決我的其余問題。
理想情況下,我想使用c#使用LINQ to XML(XElement,XNamespace等),但如果使用XmlDocuments和XmlElements可以更容易/更好地實現這一點,我會繼續使用它。
謝謝!!!
這是一個創建所需輸出的小例子:
using System;
using System.Xml.Linq;
class Program
{
static void Main()
{
XNamespace ci = "http://somewhere.com";
XNamespace ca = "http://somewhereelse.com";
XElement element = new XElement("root",
new XAttribute(XNamespace.Xmlns + "ci", ci),
new XAttribute(XNamespace.Xmlns + "ca", ca),
new XElement(ci + "field1", "test"),
new XElement(ca + "field2", "another test"));
}
}
試試這段代碼:
string prefix = element.GetPrefixOfNamespace(element.Name.NamespaceName);
string name = String.Format(prefix == null ? "{1}" : "{0}:{1}", prefix, element.Name.LocalName);`
我希望你能從這個線程中獲得一些有用的信息 - 屬性上的XElement默認命名空間提供了意想不到的行為
編輯:
另一個常見問題解答 - http://social.msdn.microsoft.com/Forums/en-US/xmlandnetfx/thread/c0648840-e389-49be-a3d2-4d5db17b8ddd
XNamespace ci = "http://somewhere.com";
XNamespace ca = "http://somewhereelse.com";
XElement root = new XElement(aw + "root",
new XAttribute(XNamespace.Xmlns + "ci", "http://somewhere.com"),
new XAttribute(XNamespace.Xmlns + "ca", "http://somewhereelse.com"),
new XElement(ci + "field1", "test"),
new XElement(ca + "field2", "another test")
);
Console.WriteLine(root);
這應該輸出
<root xmlns:ci="http://somewhere.com" xmlns:ca="http://somewhereelse.com">
<ci:field1>test</ci:field1>
<ca:field2>another test</ca:field2>
</root>
對於XmlDocument,它是類似的:
XmlAttribute attribute1 = sessionXml.CreateAttribute("s", "Attribute1", namespaceURI);
XmlAttribute attribute2 = sessionXml.CreateAttribute("s", "Attribute2", namespaceURI);
XmlAttribute attribute3 = sessionXml.CreateAttribute("s", "Attribute3", namespaceURI);
XmlAttribute attribute4 = sessionXml.CreateAttribute("s", "Attribute4", namespaceURI);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.