我正在通过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
答案 0 :(得分: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);
}