【问题标题】:XDocument LINQ search based on attribute基于属性的 XDocument LINQ 搜索
【发布时间】:2014-04-07 12:58:42
【问题描述】:

我有一个从磁盘加载的 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”

这段代码有什么问题?

【问题讨论】:

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


    【解决方案1】:

    您可以使用Descendants-Method 来获取您的 NarrationEvent-Element。我已经相应地更新了您的代码。

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

    【讨论】:

    • 看来你是对的,但我不明白其中的逻辑。 evets.Elements() 只查看根?
    • @A.A. Elements() 仅检查节点的直接子节点,而 Descendants() 则检查所有直接和间接子节点
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多