如果元素包含值,则从xml中获取这些元素



如何获取具有特定RId的每个对象中的所有对象和所有用户
例如:
对于RId "r4",我应该得到:

obj3: u1
obj6: u2,u5

我的xml是这样的:

<Objects>
  <Object id="obj2" Name="Object 2">
    <Users>
      <User id="u1" RId="r1" />
      <User id="u2" RId="r3" />
    </Users>
  </Object>
  <Object id="obj3" Name="Object 3">
    <Users>
      <User id="u2" RId="r5" />
      <User id="u3" RId="r2" />
      <User id="u1" RId="r4" />
    </Users>
  </Object>
  <Object id="obj6" Name="Object 6">
    <Users>
      <User id="u1" RId="r1" />
      <User id="u2" RId="r4" />
      <User id="u5" RId="r4" />
    </Users>
  </Object>
</Objects>

使用

        XDocument doc = XDocument.Load("../../XMLFile1.xml");
        IEnumerable<string> query = from obj in doc.Descendants("Object")
                                    let users = obj.Element("Users").Elements("User").Where(u => u.Attribute("RId").Value == "r4")
                                    where users.Any()
                                    select obj.Attribute("id").Value + ": " + String.Join(", ", users.Attributes("id").Select(a => a.Value));
        foreach (string s in query)
        {
            Console.WriteLine(s);
        }

林奇的方法

XDocument doc = XDocument.Parse(xml);
var q = doc.Descendants("Object")
    .Select(o => new
    {
        ObjId = o.Attribute("id"),
        UserIds = o.Descendants("User").Where(u => u.Attribute("RId").Value == "r4").Select(u => u.Attribute("id"))
    }).Where(x => x.UserIds.Any());

相关内容

  • 没有找到相关文章

最新更新