我不相信仅使用 XPaths 是可能的,但使用 XSLT 绝对是可能的。
这个 XSLT:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="div[@class='category']">
<div>
<div class="category">
<xsl:value-of select="."/>
</div>
<div>
<xsl:variable name="nextCategoryCount" select="count(following-sibling::div[@class='category'])"/>
<xsl:for-each select="following-sibling::div[count(following-sibling::div[@class='category']) = $nextCategoryCount]">
<xsl:copy-of select="."/>
</xsl:for-each>
</div>
</div>
</xsl:template>
<xsl:template match="/html">
<html>
<xsl:apply-templates select="div[@class='category']"/>
</html>
</xsl:template>
</xsl:stylesheet>
应用于示例 XML 会产生以下结果:
<html>
<div>
<div class="category">Name:</div>
<div>
<div class="category1">Company ABC</div>
</div>
</div>
<div>
<div class="category">ID:</div>
<div>
<div class="category1">1</div>
</div>
</div>
<div>
<div class="category">Location:</div>
<div>
<div class="category1">Home ABC</div>
<div class="category1">Home DEF</div>
</div>
</div>
</html>
这项工作由 XPath 完成:
following-sibling::div[count(following-sibling::div[@class='category']) = $nextCategoryCount]
where$nextCategoryCount
设置为当前类别之后的类别数。这不能在纯 XPath 中工作,因为在执行表达式之前无法设置该变量。