XSLT排序XML部分节点时丢失同级字段问题
问题排查与解决方案
你的问题根源很明确:在匹配employment_information的模板里,你只对job_information节点做了排序处理,完全忽略了employment_information下的其他同级字段(也就是你提到的那些fields...fields),所以这些节点才会被意外删除。
要解决这个问题,我们只需要在保留现有排序逻辑的基础上,把employment_information下除job_information之外的所有子节点也一并处理输出即可。
修正后的XSLT代码
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" encoding="UTF-8" indent="yes"/> <!-- 身份转换模板:默认复制所有节点和属性,保证非目标节点的结构完整 --> <xsl:template match="@* | node()"> <xsl:copy> <xsl:apply-templates select="@* | node()"/> </xsl:copy> </xsl:template> <!-- 处理employment_information节点:先保留其他同级节点,再排序输出job_information --> <xsl:template match="employment_information"> <xsl:copy> <!-- 先输出所有非job_information的子节点,保留原有字段 --> <xsl:apply-templates select="node()[not(self::job_information)]"/> <!-- 再对job_information按end_date字段排序输出 --> <xsl:apply-templates select="job_information"> <!-- 拼接日期字符串为可排序的格式 --> <xsl:sort select="concat( substring(end_date, 1, 4), substring(end_date, 6, 2), substring(end_date, 9, 2) )" order="ascending"/> </xsl:apply-templates> </xsl:copy> </xsl:template> </xsl:stylesheet>
关键修改说明
- 新增的
<xsl:apply-templates select="node()[not(self::job_information)]"/>语句,会匹配并输出employment_information下所有不属于job_information的子节点,完美保留了你需要的同级字段。 - 原有的日期排序逻辑完全保留,只是调整了处理顺序:先输出其他节点,再输出排序后的
job_information(你可以根据实际需求调换两者的输出顺序)。
这样修改后,既实现了job_information按end_date排序的核心需求,又不会丢失employment_information下的其他同级节点结构。
内容的提问来源于stack exchange,提问作者Eric C.
相关产品推荐
相关产品推荐

