XDocument LINQ基于属性的搜索

时间:2014-04-07 12:58:43

标签: c# xml linq linq-to-xml xelement

我有一个从磁盘加载的XML文档

XDocument events = XDocument.Load("Content/GameData/events.xml");

此xml的内容如下:

<?xml version='1.0' encoding='UTF-8'?>
<Events>
    <level1>
        <NarrationEvent code="lvl1_fridge">
        I can't even remember when I last ate.
        I am not hungry though.
        </NarrationEvent>
        <NarrationEvent code="lvl1_tv">
        Why do I even have a TV?
        Oh right, I use it as a screen for my laptop.
        </NarrationEvent>
        <NarrationEvent code="lvl1_bed">
        Oh man, I am beat.
        </NarrationEvent>
        <NarrationEvent code="lvl1_computer">
        Oh, look at that. The project has been compiled.
        </NarrationEvent>
    </level1>
    <level2>

    </level2>
    <level3>

    </level3>
    <level4>

    </level4>
    <cave>

    </cave>
</Events>

我在这里使用这段代码据说根据其属性“code”选择合适的NarrationEvent元素

IEnumerable<XElement> v =
            (from narrationEvent in events.Elements("NarrationEvent")
             where  (string)narrationEvent.Attribute("code") == code
             select narrationEvent);


foreach (XElement page in v)
{
    //Console.WriteLine("ff");
    narration.Add(page.Value);

}

这不返回任何内容,我的XElement Ienumerable为空。我使用断点,代码值传递给这个方法就好了。例如“lvl1_bed”

此代码有什么问题?

1 个答案:

答案 0 :(得分:0)

您可以使用Descendants - 方法获取NarrationEvent-Element。我已相应更新了您的代码。

IEnumerable<XElement> v = from narrationEvent in events.Descendants("NarrationEvent")
                          where narrationEvent.Attribute("code").Value == code
                          select narrationEvent;