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

时间:2014-04-08 11:13:29

标签: xml linq linq-to-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>

2 个答案:

答案 0 :(得分:0)

使用

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

答案 1 :(得分:0)

LINQish这样做的方式

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