xml - 在XSLT处理期间是否可以导航到匹配节点的父节点?

标签 xml xslt xpath parent

我正在处理OpenXML文档,并使用一些XSLT处理主要文档部分。

我通过选择了一组节点

<xsl:template match="w:sdt">
</xsl:template>


在大多数情况下,我只需要用其他东西替换那个匹配的节点,就可以了。

但是,在某些情况下,我不需要替换匹配的w:sdt节点,而是最接近的w:p祖先节点(即包含sdt节点的第一段节点)。

诀窍在于,用于决定一个或另一个的条件是基于从sdt节点的属性派生的数据,因此我不能使用典型的xslt xpath过滤器。

我正在尝试做这样的事情

<xsl:template match="w:sdt">
  <xsl:choose>
    <xsl:when test={first condition}> 
        {apply whatever templating is necessary}
    </xsl:when> 
    <xsl:when test={exception condition}> 
      <!-- select the parent of the ancestor w:p nodes and apply the appropriate templates -->
      <xsl:apply-templates select="(ancestor::w:p)/.." mode="backout" />
    </xsl:when> 
  </xsl:choose> 
</xsl:template>


<!-- by using "mode", only this template will be applied to those matching nodes
     from the apply-templates above -->
<xsl:template match="node()" mode="backout">
  {CUSTOM FORMAT the node appropriately}
</xsl:template>


整个概念都有效,但是无论我尝试了什么,它始终将CUSTOM FORMAT模板的格式应用于w:p节点,而不是其父节点。

几乎就像您无法从匹配节点中引用父级。也许您不能,但是我还没有找到任何文档说您不能

有任何想法吗?

最佳答案

这个:

<xsl:apply-templates select="(ancestor::w:p)/.." mode="backout" />


将查找作为上下文节点祖先的所有w:p元素,并将模板应用于每个父元素。在我看来,也许您想要做的就是仅找到最近的祖先,例如:

<xsl:apply-templates select="ancestor::w:p[1]/.." mode="backout" />


但是,您在此处描述的内容应该以某种方式起作用。您可能应该通过将backout模板替换为更具诊断性的内容来验证您认为正在发生的事情实际上是正在发生的事情,例如:

<xsl:template match="node()" mode="backout">
   <xsl:text>backout matched a </xsl:text>
   <xsl:value-of select="name()"/>
   <xsl:text> element.</xsl:text>
</xsl:template>

关于xml - 在XSLT处理期间是否可以导航到匹配节点的父节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2563644/

相关文章:

javascript - 使用 javascript xml 解析器在 XMLnode 中插入属性

java - 当使用 java 在 xsl 样式表的帮助下替换 xml 元素时,没有被替换

c# - 如何在 XPath 中搜索空/无效节点/元素?

python - Selenium - 识别网页元素

xml - 将 XML 命名空间属性添加到第 3 方 xml?

php - 在 PHP 中将 & 转换为 & for XML

xml - 遍历数组并根据优先级进行选择

javascript - 排除 xml 节点

xml - XPath,其中要求适用于比结果集中的节点更深的节点

android - 在多个 textView 中设置 textColor