首页 > 解决方案 > 是否可以使用 XPath 获得此结果集?

问题描述

我有一些 XML,我使用 javascript 和 XPath (1.0) 作为学习过程。我可以处理基本的事情,但把它们放在一起就是让我把头发拉出来。

我的 XML 文件包含多本这样格式的书籍。

<bookstore>     <!-- Added by edit -->
    <book category="Fantasy &amp; Adventure" cover="paperback" released="true" special="true" homepage="true">
        <title>Belgariad 1: Pawn of Prophecy</title>
        <artwork>david-eddings-belgariad-1.jpg</artwork>
        <author>David Eddings</author>
        <year>2006</year>
        <price>7.99</price>
        <rating>
            <score>4</score>
            <amount>340</amount>
        </rating>
        <description>
            <short>An ancient prophecy &amp; and a maimed God...--nl--Long ago, the evil God Torak fought a war to obtain an object of immense power - the Orb of Aldur.But Torak was defeated and the Orb reclaimed by Belgarath the sorcerer.</short>
            <long>Garion, a young farm lad, loves the story when he first hears it from the old storyteller. But it has nothing to do with him. Or does it? For the stories also tell of a prophecy that must be fulfilled - a destiny handed down through the generations.--nl--And Torak is stirring again...</long>
        </description>
        <reviews>
            <review>
                <source>Anne McCaffrey</source>
                <text>Fabulous.</text>
            </review>
            <review>
                <source>Darren Shan</source>
                <text>Fun, exciting, intriguing fantasy in which the characters are as important as the quest and magical elements... immerse yourself and enjoy!</text>
            </review>
        </reviews>
    </book>
</bookstore>

我正在尝试获取一组包含标题、艺术品、价格、描述/简短、评级/分数和评级/金额的节点。我可以使用谓词轻松获得标题、艺术品和价格(见下文),但我已经尝试了 self::、child::、descendant:: 等的每种组合大约 48 小时,但我无法让它工作。有人能够让我摆脱痛苦并告诉我这是否可能吗?

我最接近的 XPath 是:

/bookstore/book[@special='true' and @homepage='true']/*[self::title | self::artwork | self::price]

这让我按顺序获得了这 3 个元素(标题、艺术品、价格;标题、艺术品、价格等),但如果我添加类似 self::description/short 或 child::*/short 的任何内容,我将不会得到任何返回的描述。

最坏的情况是我可以单独访问所有部分。

标签: javascriptxmlxpath

解决方案


descendant-or-self::如果元素名称是唯一的,您可以对轴使用这种简单的方法:

/bookstore/book[@special='true' and @homepage='true']/descendant-or-self::*[self::title | self::artwork | self::price | self::short | self::score | self::amount]

它的输出是:

Belgariad 1: Pawn of Prophecy 
david-eddings-belgariad-1.jpg 
7.99 
4 
340 
An ancient prophecy &amp; and a maimed God...--nl--Long ago, the evil God Torak fought a war to obtain an object of immense power - the Orb of Aldur.But Torak was defeated and the Orb reclaimed by Belgarath the sorcerer.

如果它们不是唯一的,则需要指定父级,parent::在谓词中使用轴:

/bookstore/book[@special='true' and @homepage='true']/descendant-or-self::*[self::title | self::artwork | self::price | self::short[parent::description] | self::score[parent::rating] | self::amount[parent::rating]]

此示例中的输出应相同。

请注意,输出的顺序是源文件顺序,而不是 XPath 表达式的顺序。


推荐阅读