Solved

C#, LINQ and XML - Get Value

Posted on 2012-04-11
4
675 Views
Last Modified: 2012-06-27
Hi experts,

I have this XML, which I am not allowed to change. My question is how to use LINQ and select the name,phone,key2 and val2 from this XML?

<Root>
 <OrganisationList>
  <Organization>
    <Name>xxx</Name>
    <Phone>yyy</Phone>
    <Features>
     <Feature>
      <Key>key1</Key>
      <Val>val1</Val>
     </Feature>
     <Feature>
      <Key>key2</Key>
      <Val>val2</val>
     </Feature>
     ...
    <Features>
  </Organization>

  <Organization>
     ...
  </Organization>
 </OrganisationList>
</Root>

just to be specific on the query, What I need is a query which returns the organization with the name,phone,key2 and val2 where the key2 value of the organization is val2 .

I hope someone can help!
0
Comment
Question by:masterpass
  • 2
4 Comments
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 500 total points
ID: 37836105
I don't fully understand the criteria you mention in your last paragraph, but see if this is what you are after:

using System;
using System.Linq;
using System.Xml.Linq;

...

static void Main(string[] args)
{
    XDocument xdoc = XDocument.Load("input.xml");

    var query = from org in xdoc.Descendants("Organization")
                from feature in org.Element("Features").Elements()
                where feature.Element("Val") != null && feature.Element("Val").Value == "val2"
                select new
                {
                    Name = org.Element("Name").Value,
                    Phone = org.Element("Phone").Value,
                    Key2 = feature.Element("Key").Value,
                    Val2 = feature.Element("Val").Value
                };

    foreach (var item in query)
    {
        Console.WriteLine(item.Name);
        Console.WriteLine(item.Phone);
        Console.WriteLine(item.Key2);
        Console.WriteLine(item.Val2);
        Console.WriteLine();
    }

    Console.ReadKey();
}

Open in new window

0
 
LVL 13

Expert Comment

by:agarwalrahul
ID: 37836138
static XDocument GetStarbuzzData()
{
     /*
         * You can use an XDocument to create an XML file, and that includes XML
         * files you can read and write using DataContractSerializer.
         *
         * An XMLDocument object represents an XML document. It's part of the
         * System.Xml.Linq namespace.
         *
         * Use XElement objects to create elements under the XML tree.
         */
 
     XDocument doc = new XDocument(
         new XDeclaration("1.0", "utf-8", "yes"),
         new XComment("Starbuzz Customer Loyalty Data"),
         new XElement("starbuzzData",
             new XAttribute("storeName", "Park Slope"),
             new XAttribute("location", "Brooklyn, NY"),
             new XElement("person",
                 new XElement("personalInfo",
                     new XElement("name", "Janet Venutian"),
                     new XElement("zip", 11215)),
                 new XElement("favoriteDrink", "Choco Macchiato"),
                 new XElement("moneySpent", 255),
                 new XElement("visits", 50)),
             new XElement("person",
                 new XElement("personalInfo",
                     new XElement("name", "Liz Nelson"),
                     new XElement("zip", 11238)),
                 new XElement("favoriteDrink", "Double Cappuccino"),
                 new XElement("moneySpent", 150),
                 new XElement("visits", 35)),
             new XElement("person",
                 new XElement("personalInfo",
                     new XElement("name", "Matt Franks"),
                     new XElement("zip", 11217)),
                 new XElement("favoriteDrink", "Zesty Lemon Chai"),
                 new XElement("moneySpent", 75),
                 new XElement("visits", 15)),
             new XElement("person",
                 new XElement("personalInfo",
                     new XElement("name", "Joe Ng"),
                     new XElement("zip", 11217)),
                 new XElement("favoriteDrink", "Banana Split in a Cup"),
                 new XElement("moneySpent", 60),
                 new XElement("visits", 10)),
             new XElement("person",
                 new XElement("personalInfo",
                     new XElement("name", "Sarah Kalter"),
                     new XElement("zip", 11215)),
                 new XElement("favoriteDrink", "Boring Coffee"),
                 new XElement("moneySpent", 110),
                 new XElement("visits", 15))));
     return doc;
}

please use the following link for reference:
http://broadcast.oreilly.com/2010/10/understanding-c-simple-linq-to.html
http://stackoverflow.com/questions/3763999/extract-data-from-xml-into-c-sharp-object-using-linq-to-xml-enums
http://dotnet.dzone.com/articles/using-linq-xml-query-xml-data
0
 
LVL 21

Author Comment

by:masterpass
ID: 37836155
well, that is exactly what I needed. just a small change in condition. Thanks Kaufmed :) you are a champ!

var query = from org in xdoc.Descendants("Organization")
                        from feature in org.Element("Features").Elements()
                        where feature.Element("[b]Key[/b]") != null && feature.Element("Key").Value == "[b]key2[/b]"
                        select new
                        {
                            Name = org.Element("Name").Value,
                            Phone = org.Element("Phone").Value,
                            Key2 = feature.Element("Key").Value,
                            Val2 = feature.Element("Val").Value
                        };

Open in new window

0
 
LVL 21

Author Closing Comment

by:masterpass
ID: 37836158
thanks :)
0

Featured Post

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
This Micro Tutorial will teach you how to censor certain areas of your screen. The example in this video will show a little boy's face being blurred. This will be demonstrated using Adobe Premiere Pro CS6.
Along with being a a promotional video for my three-day Annielytics Dashboard Seminor, this Micro Tutorial is an intro to Google Analytics API data.

810 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question