简体   繁体   中英

Query an xml file using linq to xml?

I have the following xml file:

<?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.

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.

You want to do the where clause on the Customer elements before getting the males. 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.

Also, if it helps, I always prefer using the LINQ Extensions for enumerable collections. 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:

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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