2013-10-20 105 views
1

輸出的我需要的是添加XML命名空間的XDocument

<ns1:collection> 
<ns1:child1>value1</ns1:child3> 
    <ns1:child2>value2</ns1:child3> 
    <ns1:child3>value3</ns1:child3> 
</ns1:collection> 

我嘗試下面的代碼做到這一點 - 但我得到一個異常-...

如何在添加命名空間這個 ??

XDocument xDoc = new XDocument(new XElement("collection", 
       new XElement("ns1:child1", value1), 
       new XElement("ns1:child2", value2), 
       new XElement("ns1:child3", value3))); 

我也嘗試使用

  XNamespace ns1 = "http://url/for/ns1";"; 

並做

  (ns1 + "child1", value1) 

,仍然沒有

+0

使用後得到的輸出/錯誤是什麼(ns1 +「child1」,value1)? –

+0

在那裏沒有任何異常 - 只是錯誤的XML出 – Yanshof

+0

這可能會幫助你。 http://stackoverflow.com/questions/1338517/how-can-i-write-xml-with-a-namespace-and-prefix-with-xelement –

回答

0

移動空間聲明,以虛構的父元素:

XDocument xDoc = new XDocument(new XElement("root", 
      new XAttribute(XNamespace.Xmlns + "ns1", ns1), 
       new XElement(ns1 + "collection", 
        new XElement(ns1 + "child1", value1), 
        new XElement(ns1 + "child2", value2), 
        new XElement(ns1 + "child3", value3)))); 
0
 XDocument xDoc = new XDocument(new XElement(ns1+"collection", 
      new XAttribute(XNamespace.Xmlns+"ns1",ns1), 
      new XElement(ns1+ "child1", value1), 
      new XElement(ns1+"child2", value2), 
      new XElement(ns1+"child3", value3))); 
+0

但是,在這我會收集與命名空間 - 我需要明確的情況下「收集」=>這是不好:( – Yanshof