views:

1342

answers:

2

I have following file:

<root>
  <Product desc="Household">
    <Product1 desc="Cheap">
        <Producta desc="Cheap Item 1" category="Cooking" />
        <Productb desc="Cheap Item 2" category="Gardening" />
    </Product1>
    <Product2 desc="Costly">
        <Producta desc="Costly Item 1" category="Decoration"/>
        <Productb desc="Costly Item 2" category="Furnishing" />
        <Productc desc="Costly Item 3" category="Pool" />
    </Product2>
  </Product>
</root>

I want to find out info like: Total items in Cheap and Costly, list of all category (like Cooking, Gardening, DEcoration...), list of sorted category and select only the Product which is 'Costly'

How can i do using LINQ. I did this till now:

 XElement xe = XElement.Load(Server.MapPath("~/product.xml"));
 ????
+2  A: 

Your XML structure is unfortunate as it uses a Product element for three levels of the hierarchy. Do you have other elements similar to the "household" one?

Assuming we only want the household ones, you can use:

Count items in each of cheap/costly

xe.Element("Product") // Select the Product desc="household" element
  .Elements() // Select the elements below it
  .Select(element => new { Name=(string) element.Attribute("desc"),
                           Count=element.Elements().Count() });

List all categories

xe.Descendants() // Select all descendant elements
  .Attributes() // All attributes from all elements
  // Limit it to "category" elements
  .Where(attr => attr.Name == "category")
  // Select the value
  .Select(attr => attr.Value)
  // Remove duplicates
  .Distinct();

To sort this, just use .OrderBy(x => x) at the end.

Select 'costly' products

xe.Descendants() // Select all elements
  // Only consider those with a "Costly" description
  .Where(element => (string) element.Attribute("desc") == "Costly")
  // Select the subelements of that element, and flatten the result
  .SelectMany(element => element.Elements());
Jon Skeet
I really need to teach myself LINQ... sounds soooo easy this way :)
balexandre
I have changed the xml and it is working..thanks for answer
I doubt Jon intended you to rename individual elements *within* the data; rather to have different names at each *level*...
Marc Gravell
Ok..sorry..You know with the earlier xml where everything was Product, when i used the first query of yours, it gives me object not set to reference error
Hmm... it should have worked fine, as I tested it with exactly the XML you gave (plus two "/" to terminate elements).
Jon Skeet
Thanks for your prompt responses. Please elaborate (plus two "/" to terminate elements)?
Your first revision ended with "<Product> <root>" instead of "</Product> </root>".
Jon Skeet
A: 

Well, personally I find it easier with XmlDocument:

    XmlDocument root = new XmlDocument();
    root.LoadXml(xml); // or .Load(path);

    var categories = root.SelectNodes(
        "/root/Product/Product/Product/@category")
        .Cast<XmlNode>().Select(cat => cat.InnerText).Distinct();
    var sortedCategories = categories.OrderBy(cat => cat);
    foreach (var category in sortedCategories)
    {
        Console.WriteLine(category);
    }

    var totalItems = root.SelectNodes(
         "/root/Products/Product/Product").Count;
    Console.WriteLine(totalItems);

    foreach (XmlElement prod in root.SelectNodes(
        "/root/Product/Product[@desc='Costly']/Product"))
    {
        Console.WriteLine(prod.GetAttribute("desc"));
    }
Marc Gravell