简体   繁体   中英

“where” query using linq xml

been taxing my brain trying to figure out how to perform a linq xml query.

i'd like the query to return a list of all the "product" items where the category/name = "First Category" in the following xml

<catalog>
  <category>
    <name>First Category</name>
    <order>0</order>
    <product>
      <name>First Product</name>
      <order>0</order>
    </product>
    <product>
      <name>3 Product</name>
      <order>2</order>
    </product>
    <product>
      <name>2 Product</name>
      <order>1</order>
    </product>
  </category>
</catalog>

Like so:

    XDocument doc = XDocument.Parse(xml);
    var qry = from cat in doc.Root.Elements("category")
              where (string)cat.Element("name") == "First Category"
              from prod in cat.Elements("product")
              select prod;

or perhaps with an anonymous type too:

    XDocument doc = XDocument.Parse(xml);
    var qry = from cat in doc.Root.Elements("category")
              where (string)cat.Element("name") == "First Category"
              from prod in cat.Elements("product")
              select new
              {
                  Name = (string)prod.Element("name"),
                  Order = (int)prod.Element("order")
              };
    foreach (var prod in qry)
    {
        Console.WriteLine("{0}: {1}", prod.Order, prod.Name);
    }

Here's an example:

        string xml = @"your XML";

        XDocument doc = XDocument.Parse(xml);

        var products = from category in doc.Element("catalog").Elements("category")
                       where category.Element("name").Value == "First Category"
                       from product in category.Elements("product")
                       select new
                       {
                           Name = product.Element("name").Value,
                           Order = product.Element("order").Value
                       };
        foreach (var item in products)
        {
            Console.WriteLine("Name: {0} Order: {1}", item.Name, item.Order);
        }

You want to use the Single extension method here. Try the following:

var category = doc.RootNode.Elements("category").Single(
    c => c.Attribute("name").Value == "First Category");
var products = category.Elements("product");

Note that this assumes you only have one category with name "First Category". If you possibly have more, I recommend using Marc's solution; otherwise, this should be the more appropiate/efficient solution. Also, this will throw an exception if any category node doesn't have a name child node. Otherwise, it should do exactly what you want.

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