简体   繁体   English

使用LINQ搜索XML文档

[英]Search XML doc with LINQ

I have an xml doc similar to this: 我有一个类似于这个的xml文档:

<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. 我想基于属性ID的值返回整个MainItem元素。 So effectively if Attribute ID is equal to 2, then give me that MainItem element back. 如果属性ID等于2,那么有效,然后返回给我MainItem元素。

I can't work out how to do this with LINQ. 我无法解决如何使用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 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以获得值:

<?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: 有了这个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) 从这里: 如何:过滤属性(XPath-LINQ到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']");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM