使用XSLT将XML的type元素移动至对应Address节点问题咨询
问题根因
你的XSLT会让所有type节点出现在每个Address块中,核心原因是选择type节点时使用了//开头的全局绝对路径,会匹配整个文档中所有符合条件的type节点,而非当前Address所属的Details下的对应type节点。同时你已经声明了各命名空间前缀,无需用local-name()匹配节点,直接用前缀匹配代码可读性更高。
修正后XSLT代码
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:rsp="rsp.com/employee/Response/v30" xmlns:res="res.com/Member/details/v1" xmlns:resp="resp.com/details/v1" version="2.0"> <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/> <xsl:template match="node() | @*"> <xsl:copy> <xsl:apply-templates select="node() | @*"/> </xsl:copy> </xsl:template> <xsl:template match="resp:Address"> <xsl:copy> <xsl:apply-templates/> <!-- 相对路径取当前Address所属Details下的type节点 --> <xsl:copy-of select="../../resp:type"/> </xsl:copy> </xsl:template> <!-- 屏蔽原Details层级的type节点输出 --> <xsl:template match="resp:Details/resp:type"/> </xsl:stylesheet>
效果说明
上述代码会保留除type之外的所有节点、属性原样输出,自动将每个Details下的type节点移动到同个Details包含的所有Address节点内部,完全匹配你给出的预期输出结果。
内容的提问来源于stack exchange,提问作者Sri
相关产品推荐
相关产品推荐

