2013-10-20 107 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