2009-08-27 92 views
19

這可能是一個初學XML問題,但我怎樣才能生成一個如下所示的XML文檔?如何使用XElement的命名空間和前綴編寫xml?

<root xmlns:ci="http://somewhere.com" xmlns:ca="http://somewhereelse.com"> 
    <ci:field1>test</ci:field1> 
    <ca:field2>another test</ca:field2> 
</root> 

如果我能得到這個寫,我能得到我的問題的其他工作。理想情況下,我希望使用LINQ to XML(XElement,XNamespace等)與c#,但如果這可以通過XmlDocuments和XmlElements更容易/更好地完成,我會去那。

謝謝!

回答

39

下面是創建您需要的輸出一個小例子:

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")); 
    } 
} 
+0

你不需要在那裏爲冒號工作?另外,不''XNamespace.Xmlns'輸出'http:// www.w3.org/2000/xmlns /'? – 2016-04-14 18:06:10

+0

@ BrainStorm.exe否如最初所回答的,代碼按預期工作。當XNamespace添加字符串時,冒號會自動添加進來。這不是必須手動執行的。 – techvice 2016-05-11 19:00:47

+0

這是[詳細說明XNamespace和字符串的添加運算符的文檔](https://msdn.microsoft.com/en-us/library/system.xml.linq.xnamespace.op_addition(v = vs.110)。 ASPX) – techvice 2016-05-11 19:15:45

-1
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); 

Th是應該輸出

<root xmlns:ci="http://somewhere.com" xmlns:ca="http://somewhereelse.com"> 
    <ci:field1>test</ci:field1> 
    <ca:field2>another test</ca:field2> 
</root> 
-1

對於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); 
2

試試這個代碼:

string prefix = element.GetPrefixOfNamespace(element.Name.NamespaceName); 
string name = String.Format(prefix == null ? "{1}" : "{0}:{1}", prefix, element.Name.LocalName);`