XSL - 以XML格式向祖父节点添加新节点

时间:2012-06-06 20:05:01

标签: xslt xslt-2.0

给出XML:

<a>
  <b>
    <c>some keyword</c>
  </b>
</a>

如果节点c包含文本“keyword”,我需要将新节点添加到父节点中,所以它看起来像

<a>
  <b>
    <c>some keyword</c>
  </b>
</a>
<x> new node X </x>

我可以将文字与表达式匹配:

<xsl:template match="//a/b/c[matches(text(),'\.*keyword\.*')]">
  <xsl:copy-of select="."/>
  <xsl:element name="x">
    <xsl:text> new node </xsl:text>
  </xsl:element>
</xsl:template>

,这导致

<a>
  <b>
    <c>some keyword</c>
    <x> new node X </x>
  </b>
</a>

我该如何解决?

1 个答案:

答案 0 :(得分:1)

您必须在匹配x的父级时添加a元素。您可以引用谓词中的任何子元素或属性。我的意思是你必须在复制时看一看父母的内容。复制a,b或c元素时这样做太晚了。

以下样式表应该可以解决问题。我现在没有任何支持XSLT2.0的处理器,所以我无法检查它,但你应该能够看到它中的逻辑。

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="*">
    <xsl:element name="{name()}">
        <xsl:apply-templates ></xsl:apply-templates>
    </xsl:element>
</xsl:template>
<xsl:template match="//*[matches(a/b/c/text() , 'keyword')]">
    <xsl:element name="{name()}">
        <xsl:apply-templates ></xsl:apply-templates>
        <xsl:element name="x">
            <xsl:text> new node </xsl:text>
        </xsl:element>
    </xsl:element>
</xsl:template>