我试图从输入 XML 文件创建输出 XML 文件。一些节点需要从输入复制到输出,一些被省略,一些节点将以某种方式修改其文本。但是除此之外,我需要从每个节点的文本中修剪空白。我认为最好的方法是使用模式或其他属性在同一组节点上调用两个模板,但我不知道如何做到这一点。节点太多,无法手动将 trim() 应用于每个节点。
删除空格的代码自行工作(来自另一个 Stackoverflow 的解决方案),但我不知道如何使用另一个模板修改 XML,然后应用这两个模板。我希望解决方案类似于:
<xsl:template match="/">
做改造工作...
跳转到 match="node()" 模板
</xsl:template>
删除空格解决方案:
<xsl:template match="node()">
<xsl:copy>
<xsl:apply-templates />
</xsl:copy>
</xsl:template>
<xsl:template match="text()">
<xsl:value-of select="normalize-space(.)" />
</xsl:template>
这是一个示例输入:
<ABC Id="64" Author="FirstName">
<Note Type="Test" ID="01">
<Note.1>string </Note.1>
<Note.2>
<Point.1>string2 </Point.1>
<Point.2>hello</Point.2>
</Note.2>
</Note>
</ABC>
预期输出:
<ABC Id="64" Author="FirstName">
<Note Type="Test" ID="01">
<Note.1>STRING</Note.1>
<Note.2>
<Point.1>string2</Point.1>
</Note.2>
</Note>
</ABC>
Note.1 是从源代码复制的,转换为大写字母并删除了空格。Note.2/Point.1 删除了空格。Note.2/Point.2 不是从源中复制的。
编辑---我当前的代码。它正确地删除了空格。但是,生成的 XML 包含源中删除了空格的每个节点,而不是仅在第一次转换中复制的那些节点。我将这些节点存储在一个变量中,然后将该变量传递到我的删除空白模板中。关于为什么删除空格的模板作用于原始集而不是变量中包含的集的任何想法?
<xsl:template match="/">
<!--Store the results in a variable called transformation_result-->
<xsl:variable name="transformation_result">
<!--Go to the normal transformation template -->
<xsl:call-template name="transformation"/>
<!--Results now in $transformation_result -->
</xsl:variable>
<!-- If you want to see what is in the variable -->
<!--<xsl:copy-of select="$transformation_result"/>-->
<!-- Go to the template that copies all input -->
<xsl:call-template name="copy_for_whitespace">
<!-- The $tranformation_result is the parameter passed in by the name of: input -->
<xsl:with-param name="input" select="$transformation_result"/>
</xsl:call-template>
</xsl:template>
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<xsl:template name="transformation">
<imp1:HIJ>
<xsl:copy-of select="/imp1:HIJ/imp1:ABC">
<?oracle-xsl-mapper-position imp1:ABC?>
</xsl:copy-of>
</imp1:HIJ>
</xsl:template>
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<xsl:template name="copy_for_whitespace" match="node()">
<xsl:param name="input"/>
<xsl:variable name="test">
<xsl:copy>
<xsl:apply-templates select="node()"/>
</xsl:copy>
</xsl:variable>
<xsl:copy-of select="$test"/>
</xsl:template>
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<xsl:template match="text()">
<xsl:value-of select="normalize-space()"/>
</xsl:template>