将带有冒号的命名空间添加到xml文件中

本文关键字:添加 xml 文件 命名空间 | 更新日期: 2023-09-27 18:22:08

我需要生成一个xml文件,如下所示:

<?xml version="1.0" encoding="utf-8"?>
<ns:Root xmlns:ns0="http://namespace">
  <Node1>
    <A>ValueA</A>
    <B>ValueB</B>
  </Node1>
</Root>

这是我的代码:

const string ns = "http://namespace";
var xDocument = new XDocument(
    new XElement("Root",
        new XAttribute(XNamespace.Xmlns + "ns0", ns),
        new XElement("Node1",
            new XElement("A", "ValueA"),
            new XElement("B", "ValueB")
        )
    )
);

但这产生了:

<?xml version="1.0" encoding="utf-8"?>
<Root xmlns:ns0="http://namespace">
  <Node1>
    <A>ValueA</A>
    <B>ValueB</B>
  </Node1>
</Root>

请注意在根节点之前缺少"ns0:"。如何添加?其他一切都应该完全一样。

将带有冒号的命名空间添加到xml文件中

试试这个

XNamespace ns = XNamespace.Get("http://namespace");
var xDocument = new XDocument(
                new XElement(ns + "Root",
                    new XAttribute(XNamespace.Xmlns + "ns0", ns),
                    new XElement("Node1",
                        new XElement("A", "ValueA"),
                        new XElement("B", "ValueB")
                        )));