繁体   English   中英

根据属性值合并XML节点(C#)

[英]Merge XML nodes based on attribute value (c#)

我需要基于attribute(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: ""
               };
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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM