日期:2014-05-18  浏览次数:20973 次

linq to xml

<?xml version="1.0" encoding="gb2312"?>
<today>
  <people id="1">
  <name>a</name>
  <department>卫生医疗</department>
  <number>1</number>
  </people>
  <people id="2">
  <name>liufeng</name>
  <department>其他部门</department>
  <number>1</number>
  </people>
  <people id="3">
  <name>bbb</name>
  <department>外联部</department>
  <number>1</number>
  </people>
  <people id="4">
  <name>aa</name>
  <department>企划部</department>
  <number>2</number>
  </people>
  <people id="5">
  <name>xiaoli</name>
  <department>人力资源部</department>
  <number>4</number>
  </people>
  <people id="6">
  <name>xiaowang</name>
  <department>人力资源部</department>
  <number>4</number>
  </people>
</today>



我想用linq查询
成这个样子

department number
卫生医疗 1
其他部门 1
外联部 1
企划部 2
人力资源部 8

在线等待
有了答案 马上结贴给分 第一个答对的
40分都给他

------解决方案--------------------
var xdoc = XDocument.Parse(xml);

foreach (var p in xdoc.Root.Elements().GroupBy(e => e.Element("department").Value))
{
Console.WriteLine("{0} {1}", p.Key, p.Sum(e => int.Parse(e.Element("number").Value)));
}

------解决方案--------------------
C# code
List<people > empList = new List<people >();
            empList.Add(new people () { ID = 1, name= "xx", department= "xx", number= "xx"});


*****


var xEle = new XElement("people ",
                from emp in empList
                select new XElement("people ",
                             new XAttribute("ID", emp.ID),
                               new XElement("name", emp.name),
                               new XElement("department", emp.department),
                               new XElement("number", emp.number),
                                                         ));
 
    xEle.Save("D:\\people .xml");

------解决方案--------------------
服了,差不多行了,SP都没说什么,你们着急什么,LZ不是也道歉了吗,无语了
------解决方案--------------------
既然顶起来了,我只看了前几楼而没有看之后的回复,我还是给个臆断的输出格式:

C# code
from c in XElement.Load(xml).Descendants("people")
    select new { department = c.Element("department").Value, number = c.Element("number").Value };