【问题标题】:Search XML doc with LINQ使用 LINQ 搜索 XML 文档
【发布时间】:2010-01-16 11:14:02
【问题描述】:

我有一个类似这样的 xml 文档:

<Root>

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

    ...
</Root>

我想根据属性 ID 的值返回整个 MainItem 元素。 如果 Attribute ID 等于 2,那么非常有效,然后将 MainItem 元素还给我。

我不知道如何使用 LINQ 执行此操作。 google 上似乎有大量信息,但我似乎无法找到我要查找的内容。

帮助不大?

TIA

:-)

【问题讨论】:

    标签: c# xml linq


    【解决方案1】:

    可能是这样的:

            XDocument doc = XDocument.Load("myxmlfile.xml");
            XElement mainElement = doc.Element("Root")
                                        .Elements("MainItem")
                                        .First(e => (int)e.Attribute("ID") == 2);
            // additional work
    

    【讨论】:

    • 请注意,如果没有匹配的元素,对.First() 的调用将引发异常。如果您想避免异常,请使用.FirstOrDefault(),如果没有找到则返回 NULL 值。
    • 我会使用(int)e.Attribute("ID") == 2
    • 我更喜欢这个而不是我的努力,我不喜欢 LINQ 的选择语法。
    • @AnthonyWJones,我采纳了你的建议。谢谢。
    【解决方案2】:

    这个怎么样:

    // 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
    }
    

    马克

    【讨论】:

    • 感谢您的帮助!非常感谢。
    【解决方案3】:

    我稍微更改了您的 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>
    

    使用这个 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();
    

    【讨论】:

    • 很好,谢谢。我认为我需要一本像样的关于 LINQ 的书……还有一些东西要添加到列表中;-)
    【解决方案4】:

    从这里: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']");
    

    【讨论】:

    • 感谢您的帮助!非常感谢。
    • 正如您可能注意到的,我只是引用了有关主题的 Microsoft 页面
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-03
    • 1970-01-01
    • 2013-10-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多