Solved

C#, LINQ and XML - Get Value

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

Space-Age Communications Transitions to DevOps

ViaSat, a global provider of satellite and wireless communications, securely connects businesses, governments, and organizations to the Internet. Learn how ViaSat’s Network Solutions Engineer, drove the transition from a traditional network support to a DevOps-centric model.

Question has a verified solution.

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

Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
Two types of users will appreciate AOMEI Backupper Pro: 1 - Those with PCIe drives (and haven't found cloning software that works on them). 2 - Those who want a fast clone of their boot drive (no re-boots needed) and it can clone your drive wh…
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…

820 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