只需评估这个 XPath 2.0 表达式:
reverse(/inventory/book/chapter[3]/preceding-sibling::chapter//title)
这是一个基于 XSLT 的验证:
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="/">
<xsl:sequence select=
"reverse(/inventory/book/chapter[3]/preceding-sibling::chapter//title)
"/>
</xsl:template>
</xsl:stylesheet>
当此转换应用于以下 XML 文档时(取自您之前的问题):
<inventory>
<book num="myBook1">
<title>Lindsy Boxer</title>
<author>James Patterson</author>
<publisher>LittleBig</publisher>
<price>18.21</price>
<chapter>
<title>Alex Cross Is Back - Chapter A</title>
<paragraph>
This is the
<emph>first</emph> paragraph.
<image file="alexCrossImage.gif"/>
afetr image...
</paragraph>
<paragraph>
This is the
<emph>second</emph> paragraph.
<image file="alexCrossImageAnother.gif"/>
afetr image...
</paragraph>
</chapter>
<chapter>
<title>Along Came A Spider - Chapter B</title>
<section>
<title>Along Came A Spider - Chapter B - section 1</title>
<paragraph>
This is the
<emph>first</emph>paragraph for chapter TWO section ONE.
<image file="Chapter_B_firstParagraphImage.gif"/>
afetr image...
</paragraph>
<paragraph>
This is the
<emph>second</emph> paragraph for chapter TWO section ONE.
<image file="Chapter_B_secondParagraphImage.gif"/>
afetr image...
</paragraph>
</section>
</chapter>
<chapter>
<title>Chapter C</title>
<paragraph>
This chapter has no images and only one paragraph
</paragraph>
</chapter>
</book>
<book num="myBook2">
<title>Jack Reacher Series</title>
<author>Lee Child</author>
<author>Jonny White</author>
<publisher>Pocket</publisher>
<price>5.99</price>
<chapter>
<title>Jack Reacher - Chapter ONE</title>
</chapter>
<chapter>
<title>Jack Reacher - Chapter TWO</title>
<paragraph>
This is the
<emph>second</emph> paragraph of SECOND book chapter TWO.
<image file="Jack_Reacher_Picture_Top_Sniper_US_Army.gif"/>
afetr image...
</paragraph>
</chapter>
</book>
<book num="myBook3">
<title>Alex Cross - Double Cross</title>
<author>James Patterson</author>
<publisher>Spectra</publisher>
<price>17.30</price>
<chapter>
<title>Alex Cross - Double Cross - Chapter A</title>
</chapter>
</book>
</inventory>
对上面的 XPath 表达式求值,并将生成的节点序列复制到输出:
<title>Along Came A Spider - Chapter B - section 1</title>
<title>Along Came A Spider - Chapter B</title>
<title>Alex Cross Is Back - Chapter A</title>
正如我们所见,该序列包含所需的元素,并且按照逆文档顺序——完全符合要求。
至于如何使用 Saxon 9.x 评估 XPath 表达式,请阅读相应的文档: http: //www.saxonica.com/documentation/xpath-api/s9api-xpath.xml其中有一个指向完整工作代码示例的指针.
更新:
在评论中,OP 表示他需要chapter
以相反的文档顺序排列元素,但它们的标题元素需要以文档顺序排列。
要实现这一点,请使用:
reverse(/inventory/book/chapter[3]/preceding-sibling::chapter)//title