如何在查询XML时在LINQ中添加OR条件?

时间:2016-08-09 16:48:45

标签: c# xml linq

问题:返回所有记录where Jon Doe =<bus_contact> <bus_sponsor>

当前代码返回记录1,那么只使用一个查询返回记录1和2需要进行哪些修改?

XML

<root>
  <row>
    <project_id>1</project_id>
    <project_name>Name1</project_name>
    <bus_contact>Jon Doe</bus_contact>
    <bus_sponsor>Bruce Wayne</bus_sponsor>
  </row>
  <row>
    <project_id>2</project_id>
    <project_name>Name2</project_name>
    <bus_contact>Peter Parker</bus_contact>
    <bus_sponsor>Jon Doe</bus_sponsor>
  </row>
</root>

C#

class Program
{
    static void Main (string[] args)
    {
        XElement main = XElement.Load ("master_list.xml");

        var results = main.Descendants ("row")
            .Descendants ("bus_contact")
            .Where (e => e.Value == "Jon Doe")
            .Select (e => e.Parent)               
            .Select (e => new {
                project_id = e.Descendants ("project_id").FirstOrDefault ().Value,
                project_name = e.Descendants ("project_name").FirstOrDefault ().Value
            });

        foreach (var result in results)
            Console.WriteLine ("{0}, {1}", result.project_id, result.project_name);
        Console.ReadLine ();
    }
}

编辑:这与可能的重复链接中指出的问题不完全相同。是的,它部分地指的是这一点,但作为一个初学者得到一个适当的上下文的答案,接受的答案提供,是非常有帮助的。

2 个答案:

答案 0 :(得分:4)

||Any结合使用,如下所示:

var results = main.Descendants("row")
    .Where(r =>
        r.Descendants("bus_contact").Any(c => c.Value == "Jon Doe")
    ||  r.Descendants("bus_sponsor").Any(c => c.Value == "Jon Doe")
    );

使用Any可以查看子项上的条件,而不会实际降级到子级别。通过选择Parent,这消除了爬树的必要性。

答案 1 :(得分:1)

如果每个row元素只有一种子元素项(bus_contactbus_sponsor等),则可以使用Element方法简化整个查询Descendants

var results =
    main.Descendants ("row")
    .Where (r => r.Element("bus_contact").Value == "Jon Doe"
              || r.Element("bus_contact").Value == "Jon Doe")
    .Select (r => new {
        project_id = r.Element("project_id").Value,
        project_name = r.Element("project_name").Value
    });