XML Get元素基于属性

时间:2013-11-08 17:26:24

标签: c# xml xelement

有人可以帮助我。我是XML和xElement的新手。 如何获得年份= 2013年的男性人数?结果应为300。

我有这个XML:

<company>
  <department>
    <departmentname>Dep 1</departmentname>
    <year id = "2012">
      <men>200</men>
      <women>1000</women>
    </year>
    <year id = "2013">
      <men>300</men>
      <women>400</women>
    </year>
  </department>
</company>

我有这段代码(不工作):

XElement company = XElement.Load(Server.MapPath(myXML.xml));
var men = (from a in company.Elements("department").Elements("year")
           where (string)a.Attribute("id").Value == "2013"
           select (string)(a.Element("men"))).ToList<string>();

4 个答案:

答案 0 :(得分:1)

使用XPath怎么样?

var xmldoc = XDocument.Parse(@"<?xml version='1.0' encoding='utf-8'?>
    <company>
      <department>
        <departmentname>Dep 1</departmentname>
        <year id = '2012'>
          <men>200</men>
          <women>1000</women>
        </year>
        <year id = '2013'>
          <men>300</men>
          <women>400</women>
        </year>
      </department>
    </company>");

Console.WriteLine(
    xmldoc.XPathSelectElement(
            "/company/department/year[@id='2013']/men").Value);

答案 1 :(得分:0)

假设你想要所有部门

int mens=company.Descendants("year")
                .Where(x=>x.Attribute("id").Value=="2013")
                .Sum(x=>int.Parse(x.Element("men").Value));

您的查询应该是

int men = (from a in company.Elements("department").Elements("year")
           where a.Attribute("id").Value == "2013"
           select int.Parse(a.Element("men").Value)).Sum();

答案 2 :(得分:0)

XElement company = XElement.Load(Server.MapPath(myXML.xml));

var txt = company.Descendants("men")
    .First(x => int.Parse(x.Parent.Attribute("id").Value) == 2013).Value;

不是很强大,但会在你的情况下完成工作,你应该明白这一点。

使用LINQ语法而不是扩展方法:

var txt =
    (from c in company.Descendants("men")
     where c.Parent.Attribute("id").Value == "2013"
     select c).First().Value;

答案 3 :(得分:0)

好的伙计们。我用过这个,它正在工作 谢谢你的帮助!

 XElement com = (from p in company.Elements("department")
                                    where (string)p.Element("departmentname").Value == "Dep 1"
                                    select p).First();



    var men= (from a in com.Elements("year")
                              where (string)a.Attribute("id") == "2013"
                              select (string)(a.Element("men"))).ToList<string>();