Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

C#, LINQ and XML - Get Value

Posted on 2012-04-11
4
Medium Priority
?
709 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
4 Comments
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 2000 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:Rahul Agarwal
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

Vim Reference Guide

Vim is a powerful text editor favored by many sysadmins and developers - here are some commands that you'll want to keep in your back pocket!

Question has a verified solution.

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

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.
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
Visualize your data even better in Access queries. Given a date and a value, this lesson shows how to compare that value with the previous value, calculate the difference, and display a circle if the value is the same, an up triangle if it increased…
In response to a need for security and privacy, and to continue fostering an environment members can turn to for support, solutions, and education, Experts Exchange has created anonymous question capabilities. This new feature is available to our Pr…

715 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