如何使用XSLT按XML属性值匹配元素并输出指定结构结果
XSLT筛选指定attribute并拆分到独立的mygrndchild节点
问题根源分析
你的XSLT代码未生效的核心原因:
- 模板匹配路径完全错误:XML中的节点是
myparent、mychild、mygrndchild,但你写的模板匹配的是parent、child、grandchild,且使用根路径匹配(如/parent),这只会匹配根节点为parent的XML,你的XML根节点是myparent,所以这些自定义模板根本不会被触发,全程使用默认的identity模板(match="@*|node()")复制整个XML。 - 重复定义模板:你写了两个
match="/attribute"的模板,后一个会覆盖前一个,且该路径本身错误(/attribute表示根节点是attribute,而你的attribute是mygrndchild的子节点)。 - 未实现拆分逻辑:需求是每个匹配的
attribute单独放在一个mygrndchild里,原代码没有处理节点拆分的逻辑。
正确的XSLT代码
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" omit-xml-declaration="yes" indent="yes"/> <!-- Identity模板:默认复制所有节点和属性,除非被其他模板覆盖 --> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <!-- 处理mygrndchild:为每个符合条件的attribute生成独立的mygrndchild --> <xsl:template match="mygrndchild"> <!-- 只处理包含name为one或two的attribute的mygrndchild --> <xsl:apply-templates select="attribute[@name='one' or @name='two']" mode="wrap"/> </xsl:template> <!-- 用mode模式包裹attribute到新的mygrndchild中 --> <xsl:template match="attribute" mode="wrap"> <!-- 复制原mygrndchild的所有属性 --> <mygrndchild> <xsl:copy-of select="../@*"/> <!-- 复制当前符合条件的attribute --> <xsl:copy-of select="."/> </mygrndchild> </xsl:template> <!-- 跳过不符合条件的attribute --> <xsl:template match="attribute[not(@name='one' or @name='two')]"/> <!-- 跳过没有符合条件attribute的mygrndchild(比如name="b"的节点) --> <xsl:template match="mygrndchild[not(attribute[@name='one' or @name='two'])]"/> </xsl:stylesheet>
转换后输出结果
<myparent> <mychild> <mygrndchild name="a" parent="1"> <attribute name="one" value="1"/> </mygrndchild> <mygrndchild name="a" parent="1"> <attribute name="two" value="1"/> </mygrndchild> </mychild> </myparent>
代码逻辑说明
- Identity模板:保留基础的复制逻辑,确保未被自定义模板覆盖的节点(如
myparent、mychild)正常输出。 - mygrndchild处理模板:遍历当前节点下所有符合条件的
attribute,通过mode="wrap"触发包裹模板。 - 包裹模板:为每个符合条件的
attribute生成一个新的mygrndchild,复制原节点的所有属性,并嵌入当前attribute。 - 跳过模板:直接忽略不符合条件的
attribute,以及没有符合条件attribute的mygrndchild(比如name="b"的节点)。
内容的提问来源于stack exchange,提问作者Neo Sono
相关产品推荐
相关产品推荐

