XSLT带mode属性的命名模板无法输出预期节点数据问题
问题根因
该问题由两个错误共同导致:
- step2模式下缺少默认的节点复制模板,当处理Patient、Encounters、Diagnoses的子节点时,触发了XSLT内置默认模板:元素节点仅递归处理子节点不输出标签,文本节点直接输出内容,所以最终输出只剩下节点文本,丢失了子节点标签。
- 原有step1处理逻辑是每个节点单独生成过滤片段后立即执行step2,没有先完成全文档过滤再统一执行第二步处理,结构流转逻辑不符合你设计的两步处理预期。
修复方案
修改后的XSLT代码如下:
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:math="http://www.w3.org/2005/xpath-functions/math" xmlns:map="http://www.w3.org/2005/xpath-functions/map" xmlns:array="http://www.w3.org/2005/xpath-functions/array" exclude-result-prefixes="#all" version="3.0"> <xsl:output method="xml" indent="yes"/> <xsl:variable name="encounterNumbers"> <EncounterNumber>2</EncounterNumber> </xsl:variable> <!-- 入口:先全量执行step1过滤得到完整文档,再统一走step2处理 --> <xsl:template match="/"> <xsl:variable name="filteredDoc"> <xsl:apply-templates mode="step1"/> </xsl:variable> <xsl:apply-templates select="$filteredDoc/*" mode="step2"/> </xsl:template> <!-- STEP1 通用复制模板 + 过滤规则 --> <xsl:template mode="step1" match="node()|@*"> <xsl:copy> <xsl:apply-templates select="node()|@*" mode="step1"/> </xsl:copy> </xsl:template> <xsl:template mode="step1" match="//Encounters/Encounter[not(EncounterNumber = $encounterNumbers/EncounterNumber)]"/> <xsl:template mode="step1" match="//Diagnoses/Diagnosis[not(EncounterNumber = $encounterNumbers/EncounterNumber)]"/> <!-- STEP2 业务处理模板 + 通用复制模板 --> <xsl:template mode="step2" match="Patient"> <xsl:copy-of select="." /> </xsl:template> <xsl:template mode="step2" match="Encounters|Diagnoses"> <xsl:copy-of select="." /> </xsl:template> <xsl:template mode="step2" match="node()|@*"> <xsl:copy> <xsl:apply-templates select="node()|@*" mode="step2"/> </xsl:copy> </xsl:template> </xsl:stylesheet>
输出结果
修复后输出的XML保留完整节点结构,符合预期:
<?xml version="1.0" encoding="UTF-8"?> <Patient> <BirthTime>2001-01-01T00:00:00Z</BirthTime> </Patient> <Encounters> <Encounter> <EncounterNumber>2</EncounterNumber> <FromTime>2021-03-01T00:00:00Z</FromTime> </Encounter> </Encounters> <Diagnoses> <Diagnosis> <EncounterNumber>2</EncounterNumber> </Diagnosis> </Diagnoses>
内容的提问来源于stack exchange,提问作者user481779
相关产品推荐
相关产品推荐

