我有一个xml文件
<students>
<student>
<identity>
<key>101</key>
</identity>
<information>
<name>abc</name>
<age>12</age>
<address>xyz</address>
.....
</information>
<otherinformation>
<project>
<name>project1</name>
<duration>three months</duration>
</project>
.......
</otherinformation>
</student>
<student>
<identity>
<key>102</key>
</identity>
<information>
<name>def</name>
<age>12</age>
<address>uvw</address>
.....
</information>
<otherinformation>
<project>
<name>project2</name>
<duration>one month</duration>
</project>
</otherinformation>
</student>
</students>
因此,给定密钥101的值,我想将信息节点和otherinformation
复制到所有学生,无论他们拥有什么密钥。因此,在这种情况下,具有密钥102的学生将具有与复制后的密钥101中相同的信息和otherinformation
节点。
我怎样才能做到这一点。?
答案 0 :(得分:1)
试试这个
XDocument d = XDocument.Parse(xml);
var students = d.Descendants("student").ToList();
var student101 = students.First(i => i.Element("identity").Element("key").Value == "101");
foreach (var student in students)
{
student.Descendants("information").Single().ReplaceWith(student101.Descendants("information").Single());
}
var x = d.ToString();
https://msdn.microsoft.com/en-us/library/system.xml.linq.xdocument%28v=vs.110%29.aspx