XSLT 转换期间在输出文档中的特定点插入元素 [英] Insert element at specific point in output document during XSLT transformation
问题描述
我想知道您是否可以在处理过程中访问结果文档.
I am wondering if you can access the result-document during processing.
我问的原因是我正在转换输入文档并希望根据某些条件插入元素,但这必须在我遍历树并且我即将创建它时发生.
The reason I ask is that I am transforming an input document and would like to insert elements depending on some conditions but this would have to occur when I have traversed the tree and I am nearly at end of creating it.
转换后的 xml 看起来类似于:
The transformed xml looks something similar to this:
<xform>
<xforms>
<model>
<instance>
<data />
<data />
</instance>
</model>
<bind />
<bind />
<bind />
</xforms>
</xform>
我打算在转换期间(在上述 xml 序列化之前)访问
标记并插入额外的 元素.
I intend, during transformation (before the above xml is serialized), to access the <instance>
tag and insert additional <data>
elements.
注意输入文档与上面的 xml 不同——上面的 xml 是转换应该产生的.
Note The input document is different from the above xml - the above xml is what the transformation should produce.
同样,我想访问
元素并插入额外的
节点.
Similarly, I would want to access the <xform>
element and insert additional <bind>
nodes.
所以最终文档看起来像这样(假设我添加了 2 个数据节点和 2 个绑定节点):
So the final document would look like this (assuming I added 2 data nodes and 2 bind nodes):
<xform>
<xforms>
<model>
<instance>
<data />
<data />
<data>new data node</data>
<data>second new data node</data>
</instance>
</model>
<bind />
<bind />
<bind />
<bind>new bind node</bind>
<bind>second new bind node</bind>
</xforms>
</xform>
感谢任何帮助.
推荐答案
不,您不能访问结果文档,但是您可以在变量中创建临时树,然后再次处理它们,如果需要使用不同的模板模式.所以而不是例如
No, you can't access a result-document, you can however create temporary trees in variables and then process them again, if needed with templates with a different mode. So instead of e.g.
<xsl:template match="/">
<xsl:result-document href="example.xml">
<xform>
<xforms>
<model>
<instance>
<data>
</data>
</instance>
</model>
<bind />
<bind />
<bind />
</xforms>
</xform>
</xsl:result-document>
</xsl:template>
你会在一个变量中创建第一个结果,然后进一步处理它,例如
you would create the first result in a variable and then process it further as in e.g.
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="/">
<xsl:variable name="temp1">
<xform>
<xforms>
<model>
<instance>
<data>
</data>
</instance>
</model>
<bind />
<bind />
<bind />
</xforms>
</xform>
</xsl:variable>
<xsl:result-document href="example.xml">
<xsl:apply-templates select="$temp1/*"/>
</xsl:result-document>
</xsl:template>
<xsl:template match="instance">
<xsl:copy>
<xsl:apply-templates/>
<data>...</data>
</xsl:copy>
</xsl:template>
该示例不使用模式,但我经常将它们与变量和不同的处理步骤一起使用,以将每个步骤的模板与其他步骤干净地分开.
That sample does not use modes but I often use them with variables and different processing steps to cleanly seperate the templates for each step from other steps.
这篇关于XSLT 转换期间在输出文档中的特定点插入元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!