我需要根据属性(id)的值合并XMLnodes元素,并使用C#生成结果到列表
这是原始的XML文件:
<profiles>
<profile id="1" >
<name>John</name>
<age>23</age>
<sex>male</sex>
</profile >
<profile id="2" >
<name>Mark</name>
<age>60</age>
</profile >
<profile id="2" >
<sex>male</sex>
</profile >
</profiles>
我需要按原样处理:
<profiles>
<profile id="1" >
<name>John</name>
<age>23</age>
<sex>male</sex>
</profile >
<profile id="2" >
<name>Mark</name>
<age>60</age>
<sex>male</sex>
</profile >
</profiles>
这是我的试用但它没有返回
var employee = from emp in fileDoc.Descendants("profile")
group emp by (string) emp.Attribute("id")
into emps
select new Data
{
ID =emps.Last().Attribute("id") != null ? emps.Last().Attribute("id").Value: "",
ProfileName =emps.Elements("name") != null? emps.Elements("name").Last().Value: "",
Sex=emps.Elements("sex") != null? emps.Elements("sex").Last().Value: ""
};
答案 0 :(得分:2)
var xDoc = XDocument.Parse(xml); //or XDocument.Load(fileName)
var newXDoc = new XElement("profiles",
xDoc.Descendants("profile")
.GroupBy(p => p.Attribute("id").Value)
.Select(p => new XElement("profile",
new XAttribute(p.First().Attribute("id")),
p.Elements())));
string newxml = newXDoc.ToString();