XSL 1.0技术问题:如何替换包含子标签的外层标签?
在XSL 1.0中替换包含指定子标签的外层标签
要实现仅替换包含<childtag>子标签的<tag1>为<replacedtag>,可以通过XSLT的模板匹配机制完成,核心是精准定位符合条件的节点并替换外层标签,同时保留内部内容。
完整XSLT代码示例
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <!-- 匹配所有包含childtag子元素的tag1节点 --> <xsl:template match="tag1[childtag]"> <replacedtag> <!-- 复制当前节点的所有子节点(包括文本、子标签等) --> <xsl:copy-of select="node()"/> </replacedtag> </xsl:template> <!-- 通用模板:复制所有未被匹配的节点和属性,保证文档其他结构不变 --> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> </xsl:stylesheet>
代码说明
- 匹配规则:
tag1[childtag]是XPath表达式,会选中所有直接或间接包含<childtag>子元素的<tag1>节点;如果需要仅匹配直接子节点,可改为tag1[./childtag]。 - 替换逻辑:对于匹配到的
<tag1>,输出<replacedtag>作为外层标签,并用<xsl:copy-of select="node()"/>完整保留原节点内的所有内容(文本、子标签、注释等)。 - 通用模板:确保XML中其他未被特殊匹配的节点(比如不包含
<childtag>的<tag1>、其他标签、属性等)都能原样复制,避免破坏原有文档结构。
输入输出示例
输入XML片段:
<root> <tag1> ... not-search-string ... </tag1> <!-- 1 --> <tag1> ... <childtag>content</childtag> ... </tag1> <!-- 2 --> <tag1> ... not-search-string ... </tag1> <!-- 3 --> </root>
转换后输出:
<root> <tag1> ... not-search-string ... </tag1> <!-- 1 --> <replacedtag> ... <childtag>content</childtag> ... </replacedtag> <!-- 2 --> <tag1> ... not-search-string ... </tag1> <!-- 3 --> </root>
内容的提问来源于stack exchange,提问作者tm1701
相关产品推荐
相关产品推荐

