簡體   English   中英

如何將XNamespace添加到XDocument的根元素?

[英]How to add XNamespace to XDocument's root element?

我正在通過Linq To Xml生成Xml Documemnt。 它會將'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

它需要向每個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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM