0

下面是我的 HAP 的示例输入。

<?xml version="1.0" encoding="UTF-8"?>

<html>
  <div class="category">Name:</div>
  <div class="category1">Company ABC</div>
  <div class="category">ID:</div>
  <div class="category1">1</div>
  <div class="category">Location:</div>
  <div class="category1">Home ABC</div>
  <div class="category1">Home DEF</div>
</html>

使用XPath是否可以捕获由前一个元素属性值分隔的元素的后续兄弟?在这种情况下,我想将它存储在一个列表中:

"Name" , {"Company ABC"}
"ID", {"1"}
"Location", {"Home ABC", "Home DEF"}
4

1 回答 1

0

我不相信仅使用 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 中工作,因为在执行表达式之前无法设置该变量。

于 2013-02-18T19:57:31.263 回答