开发者

Search XML doc with 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'开发者_如何学Got 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

:-)


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


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


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();


From here: How to: Filter on an Attribute (XPath-LINQ to XML)

// LINQ to XML query
IEnumerable<XElement> list1 =
    from el in items.Descendants("MainItem")
    where (string)el.Attribute("ID") == "2"
    select el;

// XPath expression
IEnumerable<XElement> list2 = items.XPathSelectElements(".//MainItem[@ID='2']");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜