我有一个xml文件定义如下:
<test>
<years year ="2001">
</test>
<test>
<years year ="2002">
</test>
<test>
<years year ="20013">
</test>
如何获取文件xml中存在的所有属性,并将其添加到其中?这样的事情:
<test>
<years>2001,2002,2003</years>
</test>
<test>
<years year ="2001">
</test>
<test>
<years year ="2002">
</test>
<test>
<years year ="2003">
</test>
非常感谢提前
答案 0 :(得分:1)
请注意,您的xml示例无效。您已添加根元素并关闭years
检查出来:
输入xml文件:
<root>
<test>
<years year="2001" />
</test>
<test>
<years year="2002" />
</test>
<test>
<years year="20013" />
</test>
</root>
代码:
[Fact]
public void Test()
{
XElement root = XElement.Load("data.xml");
var years = string.Join(",", root.Descendants("years").Select(x => x.Attribute("year").Value));
root.Add(new XElement("test", new XElement("years", years)));
root.Save("data.xml");
}
结果文件:
<?xml version="1.0" encoding="utf-8"?>
<root>
<test>
<years year="2001" />
</test>
<test>
<years year="2002" />
</test>
<test>
<years year="20013" />
</test>
<test>
<years>2001,2002,20013</years>
</test>
</root>