【问题标题】:Add xml namespace to XDocument将 xml 命名空间添加到 XDocument
【发布时间】:2023-03-24 14:26:01
【问题描述】:

我需要的输出是

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

还是什么都没有

【问题讨论】:

  • 使用 (ns1 + "child1", value1) 后得到的输出/错误是什么?
  • 这里没有例外——只是错误的 xml 输出
  • 这可能会对您有所帮助。 stackoverflow.com/questions/1338517/…

标签: c# xml


【解决方案1】:

将命名空间声明移动到虚构的父元素:

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

【讨论】:

    【解决方案2】:
            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)));
    

    【讨论】:

    • 但是在此我将拥有带有命名空间的集合 - 我需要明确情况下的“集合”=> 这不好:(
    猜你喜欢
    • 2012-12-26
    • 1970-01-01
    • 1970-01-01
    • 2017-09-21
    • 1970-01-01
    • 1970-01-01
    • 2013-09-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多