请评估此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表示他需要逆文档顺序的元素,但是它们的标题元素按文档顺序排列。
要实现这一点,请使用:
reverse(/inventory/book/chapter[3]/preceding-sibling::chapter)//title
reverse
函数,所以你可以使用XPath表达式级别来解决这个问题,例如reverse(inventory/book/chapter[3]/preceding-sibling::chapter//title)
。 - undefinedreverse(n1,n2n, nM) = (nM, n(M-1), ...n2, n1)
。你想要按照文档的相反顺序选择节点 - 当在选定的节点集上应用reverse()
函数时,这就是结果。如果你现在想要其他的,请提一个新问题。 - undefinedreverse(/inventory/book/chapter[3]/preceding-sibling::chapter)//title
。 - undefined