Linq to XML 选择子列表
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
中的所有
元素。我似乎不能这样做:(
var bq = (from c in data.behaviorlist select new { behaviour = c.Element("behaviour")});
抛出无效的语法错误)。
如何检索所有行为,不仅访问其文本,还访问属性 id
和 version
?
An example XML file is this:
<?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>
I have the query:
var data = (from item in loaded.Descendants("game")
select new
{
name = item.Element("name").Value,
behaviorlist = item.Element("behaviors-used").Value
}).Single();
Which seems to work fine. However, I need to now retrieve all the <behavior>
elements in the behaviorlist
. I can't seem to do it like this:
var bq = (from c in data.behaviorlist select new { behaviour = c.Element("behaviour")});
(Throws invalid syntax errors).
How do I retrive all the behaviours and not only access their text but also the properties id
and version
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的
behaviorlist
现在并不是真正的列表 - 您想要的是元素而不是组合文本,因此您应该检索Value
属性,而不是使用父节点的Value
属性。名称为“behavior”的 code>Elements:从结果列表中,您可以轻松检索属性:
Your
behaviorlist
is not really a list right now - you want the elements not the combined text, so instead of using theValue
property of the parent node, you should retrieve theElements
with name "behavior":From the resulting list you can then easily retrieve the properties:
id
和version
是behavior
节点的属性:id
andversion
are attributes of abehavior
node:能够让它在 LinqPad 中与您的文档一起工作:
并生成 5 个匿名对象的序列 {behaviour, id, version}
Was able to get this to work in LinqPad with your document:
and yielded a sequence of 5 anonymous objects {behaviour, id, version}