Solved

C#, LINQ and XML - Get Value

Posted on 2012-04-11
4
662 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 74

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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

The Client Need Led Us to RSS I recently had an investment company ask me how they might notify their constituents about their newsworthy publications.  Probably you would think "Facebook" or "Twitter" but this is an interesting client.  Their cons…
Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

747 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now