Linq到XML选择子列表

本文关键字:列表 选择 XML Linq | 更新日期: 2023-09-27 18:16:17

XML文件示例如下:

<?xml version="1.0" encoding="UTF-8"?>
<game>
    <name>bomber</name>
    <behaviors-used>
        <behavior id="Bullet" version="1">Bullet</behavior>
        <behavior id="Fade" version="1">Fade</behavior>
        <behavior id="Flash" version="1">Flash</behavior>
        <behavior id="Sin" version="1">Sine</behavior>
        <behavior id="scrollto" version="1">Scroll To</behavior>
    </behaviors-used>
</game>

我有查询:

var data = (from item in loaded.Descendants("game")
            select new
            {
                name = item.Element("name").Value,
                behaviorlist = item.Element("behaviors-used").Value
            }).Single();

似乎工作得很好。然而,我现在需要检索behaviorlist中的所有<behavior>元素。我似乎不能这样做:

var bq = (from c in data.behaviorlist select new { behaviour = c.Element("behaviour")});

(抛出无效语法错误)。

我如何检索所有的行为,不仅访问他们的文本,而且属性idversion ?

Linq到XML选择子列表

您的behaviorlist现在不是一个真正的列表-您想要的元素不是组合的文本,所以不是使用父节点的Value属性,您应该检索名称为"behavior"的Elements:

var data = (from item in loaded.Descendants("game")
            select new
            {
                name = item.Element("name").Value,
                behaviorlist = item.Element("behaviors-used").Elements("behavior")
            }).Single();
从结果列表中,您可以轻松地检索属性:
var bq = (from c in data.behaviorlist select new 
{ 
    id = c.Attribute("id").Value,
    version = c.Attribute("version").Value,
});

idversionbehavior节点的属性:

var items =
    xDocument.Descendants("behaviors-used")
             .Descendants("behavior")
             .Select((w, i) =>
                new
                    {
                        Index = i,
                        Value = w.Value,
                        Id = w.Attribute("id").Value,
                        Version = w.Attribute("version").Value
                    })
             .ToList();

能够在LinqPad中使用您的文档:

  var data = (from item in loaded.DescendantsAndSelf("game")
            select new{
                       name = item.Element("name").Value,
                       behaviorlist = item.Element("behaviours-used")
                      }
            ).Single();
  var bq = (from c in data.behaviorlist.Descendants("behaviour")
            select new {
                         behaviour = c.Value,
                         id = c.Attribute("id").Value,
                         version = c.Attribute("version").Value
                        });

并产生了5个匿名对象{behavior, id, version}