Avatar of Hardi
Hardi asked on

LINQ to select from XML (C# 3.0)

How do you use LINQ to select the category(ies) that has an item with code="2"?

Below is the XML
<MyItem>
        <Category name="categ1">
                <Item code="1" name="Item 1" />
                <Item code="2" name="Item 2" />
        </Category>
        <Category name="categ2">
                <Item code="3" name="Item 3" />
        </Category>
</MyItem>

Open in new window

.NET ProgrammingC#

Avatar of undefined
Last Comment
Hardi

8/22/2022 - Mon
naspinski

Here you go, let me know if you need anything explained:
XElement x = XElement.Load(Server.MapPath(".") + "\\App_Data\\sample.xml");//get your file
//grab your element
XElement elem = (from el in (from x2 in x.Descendants("Item") select x2) where el.Attribute("name").Value.Equals("Item 1") select el).First();
 
//for testing
foreach (XAttribute xa in elem.Attributes())
    Response.Write(xa.Name + " : " + xa.Value + "<br />");

Open in new window

naspinski

woops, I was testing for name = "Item 1" here is one that test for "code 2", but that is not for categories, give me a minute to get that (didnt read your question very well)
XElement x = XElement.Load(Server.MapPath(".") + "\\App_Data\\sample.xml");//get your file
//grab your element
XElement elem = (from el in (from x2 in x.Descendants("Item") select x2) where el.Attribute("code").Value.Equals("2") select el).First();
 
//for testing
foreach (XAttribute xa in elem.Attributes())
    Response.Write(xa.Name + " : " + xa.Value + "<br />");

Open in new window

margajet24

I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
ASKER CERTIFIED SOLUTION
naspinski

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
See how we're fighting big data
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
ASKER
Hardi

lol thanks naspinski!

margajet: thanks, I've seen many of those examples, they are different