简体   繁体   English

使用linq到xml查询xml文件?

[英]Query an xml file using linq to xml?

I have the following xml file: 我有以下xml文件:

<?xml version="1.0" encoding="utf-8"?>
<Cus>
  <Customer Location="NJ">
    <Male Value="True" />
    <Name Value="xxx" />
   </Customer>
  <Customer Location="NY">
    <Male Value="True" />
    <Name Value="yyy" />
   </Customer>
</Cus>

I am trying to query using the linq to xml inorder to get the value of male based on the customer location. 我试图使用linq到xml进行查询,以便根据客户位置获取男性的价值。

Here is the query: 这是查询:

  var Male = from e in doc.Descendants("Male")
             select new
             {
                 Male = e.Attribute("Value").Value.ToString()
             };

I am able to get the value of the male but i am confused how to get the name based on the location of the customer in the xml file.How to add a where condition in here which determines the location of the customer.I would appreciate if some one can guide me. 我能够获得男性的价值,但我很困惑如何根据xml文件中客户的位置获取名称。如何在此处添加确定客户位置的条件。如果有人可以指导我。

You want to do the where clause on the Customer elements before getting the males. 您想要在获取男性之前对Customer元素执行where子句。 So something like this: 所以像这样:

var males = from customer in doc.Descendants("Customer")
            where "NY".Equals(customer.Attribute("Location").Value)
            select customer.Descendants("Male");

Note: This has not been tested, but it should give you some indication of how to proceed. 注意:此操作尚未经过测试,但应为您提供一些有关如何进行操作的指示。 Check this MSDN article on the where keyword for more information. where关键字上查看此MSDN文章 ,以了解更多信息。

Also, if it helps, I always prefer using the LINQ Extensions for enumerable collections. 另外,如果有帮助,我总是喜欢将LINQ扩展用于可枚举的集合。 I find them much easier to read and write than the clause keywords. 我发现它们比子句关键字更容易读写。

Per your question - to select the value of name based on location, you could use something like: 根据您的问题-要根据位置选择name的值,可以使用类似以下内容的方法:

private string CountOfMales(XDocument doc, string locationToFilter)
{
  var selection = from customer in doc.Descendants("Customer")
                 .Where(c => c.Attribute("Location").Value == locationToFilter)
                 select new
                 {
                    MaleValue = customer.Element("Name").Attribute("Value").Value
                 };

                 return selection.FirstOrDefault().MaleValue;
}

For something like this I really like the XML extension methods SafeElement and SafeAttribute as they let you query the XML without worrying about running into null values if the XML doesn't contain the elements or attributes you specified. 对于这样的事情,我真的很喜欢XML扩展方法SafeElement和SafeAttribute,因为它们使您可以查询XML,而不必担心如果XML不包含您指定的元素或属性,便会遇到空值。

The code for these extension methods is here: 这些扩展方法的代码在这里:

    public static XElement SafeElement(this XContainer container, string name)
    {
        return container.Element(name) ?? new XElement(name);
    }

    public static XAttribute SafeAttribute(this XElement element, string name)
    {
        return element.Attribute(name) ?? new XAttribute(name, "");
    }

You use it like this: 您可以这样使用它:

        var customers = xdoc.Descendants("Customer")
                        .Where(x => x.SafeAttribute("Location").Value == "NJ")
                        .Select(x => x.SafeElement("Male").SafeAttribute("Value").Value);

If for whatever reason the Location attribute or the Male element isn't present you end up with an empty result set instead of exceptions. 如果由于某种原因不显示Location属性或Male元素,则结果将为空,而不是异常。

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

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