【发布时间】:2018-10-03 10:00:40
【问题描述】:
我希望像下面这样转换一些 XML,在此示例中只有 2 个元素可以组合在一起,但可能更多:
<file>
<patient>
<Lab_No_Spec_No>12345</Lab_No_Spec_No>
<Patient_Number>ABC</Patient_Number>
<Albumin_g_L>48 </Albumin_g_L>
<Calcium_mmol_L>
<Phosphate_mmol_L>100 </Phosphate_mmol_L>
</patient>
<patient>
<Lab_No_Spec_No>12345</Lab_No_Spec_No>
<Patient_Number>ABC</Patient_Number>
<Albumin_g_L>92 </Albumin_g_L>
<Calcium_mmol_L>50 </Calcium_mmol_L>
<Phosphate_mmol_L/>
</patient>
</file>
到以下结果:
<file>
<patient>
<Lab_No_Spec_No>12345</Lab_No_Spec_No>
<Patient_Number>ABC</Patient_Number>
<Albumin_g_L>48,92</Albumin_g_L>
<Calcium_mmol_L>50</Calcium_mmol_L>
<Phosphate_mmol_L>100</Phosphate_mmol_L>
</patient>
</file>
这是我目前的转变:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>
<xsl:strip-space elements="*"/>
<xsl:key name="specimen" match="patient" use="Lab_No_Spec_No" />
<xsl:template match="file">
<file>
<xsl:for-each select="patient[count(. | key('specimen', Lab_No_Spec_No)[1]) = 1]">
<patient>
<xsl:copy-of select="Lab_No_Spec_No" />
<xsl:copy-of select="Patient_Number" />
<Albumin_g_L>
<xsl:for-each select="key('specimen', Lab_No_Spec_No)">
<xsl:value-of select="normalize-space(Albumin_g_L)" />
<xsl:if test="position() != last()">
<xsl:text>,</xsl:text>
</xsl:if>
</xsl:for-each>
</Albumin_g_L>
<Calcium_mmol_L>
<xsl:for-each select="key('specimen', Lab_No_Spec_No)">
<xsl:value-of select="normalize-space(Calcium_mmol_L)" />
<xsl:if test="position() != last()">
<xsl:text>,</xsl:text>
</xsl:if>
</xsl:for-each>
</Calcium_mmol_L>
<Phosphate_mmol_L>
<xsl:for-each select="key('specimen', Lab_No_Spec_No)">
<xsl:value-of select="normalize-space(Phosphate_mmol_L)" />
<xsl:if test="position() != last()">
<xsl:text>,</xsl:text>
</xsl:if>
</xsl:for-each>
</Phosphate_mmol_L>
</patient>
</xsl:for-each>
</file>
</xsl:template>
</xsl:stylesheet>
上面有一些问题我正在寻求帮助:
在
<xsl:for-each select="key('specimen', Lab_No_Spec_No)">连接过程中包含了空元素,我想省略这些元素,以免得到像<Calcium_mmol_L>50,</Calcium_mmol_L>这样的结果。我的 for-each 选择需要更改什么以便不选择空元素?真正的源 XML 文件有 30 多个元素,我需要对其进行连接。我在我的示例中对 3 个元素重复了相同的转换,但是对于
Patient_Number元素之后的元素是否有一种速记方法,或者我是否必须重复转换?大致如下:
<xsl:for-each select="following-sibling::Patient_Number"> <local-name(.)> <xsl:for-each select="key('specimen', Lab_No_Spec_No)"> <xsl:value-of select="normalize-space(.)" /> <xsl:if test="position() != last()"> <xsl:text>,</xsl:text> </xsl:if> </xsl:for-each> </local-name(.)> </xsl:for-each>
【问题讨论】:
-
我猜你没有使用
xsl:for-each-group意味着你被 XSLT 1.0 困住了?如果是这样,您应该相应地标记问题,这样我们就不会浪费时间为您提供 XSLT 2.0 答案。 -
是的,已更新该标签