Xslt 测试当前(根)节点名称是否等于字符串
我有一个XML,它可能类似于以下内容之一:Xslt 测试当前(根)节点名称是否等于字符串,xslt,xslt-2.0,Xslt,Xslt 2.0,我有一个XML,它可能类似于以下内容之一: // #1 <A> <B>... stuff ...</B> </A> // #2 <B>... stuff ...</B> /#1 ... 东西 // #2 ... 东西 我需要将它们转换为一个响应节点,这两个实例的响应节点看起来应该相同。有点像这样: <fooMethodResponse> ... one thing from A if A
// #1
<A>
<B>... stuff ...</B>
</A>
// #2
<B>... stuff ...</B>
/#1
... 东西
// #2
... 东西
我需要将它们转换为一个响应节点,这两个实例的响应节点看起来应该相同。有点像这样:
<fooMethodResponse>
... one thing from A if A was root ...
... stuff from B ...
</fooMethodResponse>
<xsl:template match="/">
<fooMethodResponse>
<xsl:choose>
<xsl:when test="node name is A">
<xsl:when test="node name is B">
</xsl:choose>
</fooMethodResponse>
</xsl:template>
... 如果A是根,那么A中的一件事。。。
... B的东西。。。
我如何做到这一点而不重复我自己?我现在已经这样做了:
<xsl:template match="/A">
<fooMethodResponse>
<xsl:apply-templates select="B" mode="get-B" />
<xsl:element name="processId">
<xsl:value-of select="@id" />
</xsl:element>
</fooMethodResponse>
</xsl:template>
<xsl:template match="/B">
<fooMethodResponse>
<xsl:apply-templates select="." mode="get-B" />
</fooMethodResponse>
</xsl:template>
<xsl:template match="B" mode="get-B"></xsl:template>
这里的问题是我在重复响应包装器,我只想在一个地方使用它。我想我可以这样做:
<fooMethodResponse>
... one thing from A if A was root ...
... stuff from B ...
</fooMethodResponse>
<xsl:template match="/">
<fooMethodResponse>
<xsl:choose>
<xsl:when test="node name is A">
<xsl:when test="node name is B">
</xsl:choose>
</fooMethodResponse>
</xsl:template>
但是我不知道如何编写测试来检查根元素的节点名。根元素的处理方式是否有所不同
我想给出更精确的示例,但其中有相当多的业务内容,因此我尝试将其归结为:p我不确定您想要做什么,需要更精确的输入和输出示例。 不过,以下XSLT(1.0)可以作为解决问题的基础:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:template match="/">
<fooMethodResponse>
<xsl:apply-templates/>
</fooMethodResponse>
</xsl:template>
<xsl:template match="A">
<xsl:text>... one thing from A if A was root ...</xsl:text>
<xsl:apply-templates/>
</xsl:template>
<xsl:template match="B">
<xsl:text>... stuff from B ...</xsl:text>
</xsl:template>
</xsl:stylesheet>
... 如果A是根,那么A中的一件事。。。
... B的东西。。。
对于输入#1:
... 东西
结果#1是:
。。。如果A是根,那么A中的一件事。。。
... B的东西。。。
对于输入#2:
。。。东西
结果#2是:
。。。东西
希望这有帮助 您可以做的是将模式与
|
运算符组合,例如
<xsl:template match="/A[B] | /B">
<fooMethodResponse>...</fooMethodResponse>
</xsl:template>
...
在你的情况下,这是否有意义或简化了事情,我不确定,因为我不明白你想为两个不同的元素在
foodmethodresponse
中添加什么。考虑拼出每个可能的输入样本的每个结果样本,您当前的单个结果样本对我来说并不清楚。 SoS>代码>匹配=“//”/>代码>比<代码>匹配=“元素”< /代码>具有更高的优先级,即使<代码>元素< /代码>是“代码>/< /代码>”,这不是一个优先级问题。使用XSLT转换文档时,首先将模板应用于文档的根match=“/”
,如果定义了此模板,则它将执行模板或使用默认模板(对于根,仅执行xsl:apply templates
)。因此XSLT处理器应用的第一个模板是match=“/”
。然后,这取决于您的结构和您在第一个模板中编写的内容。对于该模板中的两种情况,B都是“this”吗?尝试采用XSLT术语,而不是OO术语。该模板中的上下文节点()是A
元素节点或B
元素节点。谢谢。xslt新手总数,很高兴能够更正术语;)
<fooMethodResponse>... stuff ...</fooMethodResponse>
<xsl:template match="/A[B] | /B">
<fooMethodResponse>...</fooMethodResponse>
</xsl:template>