Solved

C#, LINQ and XML - Get Value

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Windows 10 is mostly good. However the one thing that annoys me is how many clicks you have to do to dial a VPN connection. You have to go to settings from the start menu, (2 clicks), Network and Internet (1 click), Click VPN (another click) then fi…
Hi friends,  in this video  I'll show you how new windows 10 user can learn the using of windows 10. Thank you.

867 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

19 Experts available now in Live!

Get 1:1 Help Now