【问题标题】:How to add XNamespace to XDocument's root element?如何将 XNamespace 添加到 XDocument 的根元素?
【发布时间】:2019-05-06 19:19:28
【问题描述】:

我正在通过 Linq To Xml 生成 Xml 文档。它为所有具有空值的元素添加了“xmlns”属性。 如何删除不需要的属性?

XNamespace np = "example"; 

XDocument doc = new XDocument(
                    new XDeclaration("1.0", "UTF-8", string.Empty),
                        new XElement(np + "root")
                        );
var list = new List<string> { "1", "2", "3" };

foreach (var item in list)
{
  var xE = new XElement("child",
             new XElement("first", item),
             new XElement("second", item)
                        );
   doc.Root.AddFirst(xE);
}

我期待结果。

根元素中只有 xmlns 属性

<?xml version="1.0" encoding="utf-8"?>
<root xmlns="example">
  <child>
    <first>3</first>
    <second>3</second>
  </child>
  <child >
    <first>2</first>
    <second>2</second>
  </child>
  <child>
    <first>1</first>
    <second>1</second>
  </child>
</root>

但是得到

<?xml version="1.0" encoding="utf-8"?>
<root xmlns="example">
  <child xmlns=""> //unwanted attribute

    <first>3</first>
    <second>3</second>
  </child>
  <child xmlns="">
    <first>2</first>
    <second>2</second>
  </child>
  <child xmlns="">
    <first>1</first>
    <second>1</second>
  </child>
</root

【问题讨论】:

标签: c# xml


【解决方案1】:

需要为每个 XElement 添加 XNamespace。


XDocument doc = new XDocument(
                   new XDeclaration("1.0", "UTF-8", string.Empty),
                       new XElement(np + "root")
                   );
var list = new List<string> { "1", "2", "3" };

foreach (var item in list)
{
 var xE = new XElement(np+"child",
            new XElement(np+"first", item),
            new XElement(np+"second", item)
                       );
  doc.Root.AddFirst(xE);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-27
    • 2013-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多