Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search XML doc with LINQ

Tags:

c#

xml

linq

I have an xml doc similar to this:

<Root>

    <MainItem ID="1">
        <SubItem></SubItem>
        <SubItem></SubItem>
        <SubItem></SubItem>
    </MainItem>
    <MainItem ID="2">
        <SubItem></SubItem>
        <SubItem></SubItem>
        <SubItem></SubItem>
    </MainItem>

    ...
</Root>

I want to return the whole of the MainItem element based on the value of attribute ID. So effectively if Attribute ID is equal to 2, then give me that MainItem element back.

I can't work out how to do this with LINQ. There seems to be a load of information on google, but I just can't quite seem to find what I'm looking for.

Little help ?

TIA

:-)

like image 470
JustAPleb Avatar asked Jan 16 '10 11:01

JustAPleb


3 Answers

It could be something like this:

        XDocument doc = XDocument.Load("myxmlfile.xml");
        XElement mainElement = doc.Element("Root")
                                    .Elements("MainItem")
                                    .First(e => (int)e.Attribute("ID") == 2);
        // additional work
like image 127
bruno conde Avatar answered Oct 03 '22 18:10

bruno conde


How about this:

// load your XML
XDocument doc = XDocument.Load(@"D:\linq.xml");

// find element which has a ID=2 value
XElement mainItem = doc.Descendants("MainItem")
                          .Where(mi => mi.Attribute("ID").Value == "2")
                          .FirstOrDefault();

if(mainItem != null)
{ 
  // do whatever you need to do
}

Marc

like image 26
marc_s Avatar answered Oct 03 '22 17:10

marc_s


I changed your XML slightly to have values:

<?xml version="1.0"?>
<Root>
    <MainItem ID="1">
        <SubItem>value 1</SubItem>
        <SubItem>val 2</SubItem>
        <SubItem></SubItem>
    </MainItem>
    <MainItem ID="2">
        <SubItem></SubItem>
        <SubItem></SubItem>
        <SubItem></SubItem>
    </MainItem>
</Root>

And with this LINQ:

XDocument xmlDoc = XDocument.Load(@"C:\test.xml");
var result = from mainitem in xmlDoc.Descendants("MainItem")
             where mainitem.Attribute("ID").Value == "1"
             select mainitem;


foreach (var subitem in result.First().Descendants())
{
    Console.WriteLine(subitem.Value);
}

Console.Read();
like image 28
Chris S Avatar answered Oct 03 '22 18:10

Chris S