【发布时间】: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
【问题讨论】:
-
我通常从包含根标签的字符串创建我的 XDocument:XDocument doc = XDocument.Parse("
");