Xml xslt中的多条件检查
我使用的是XSLT2.0 我有以下xmlXml xslt中的多条件检查,xml,xslt,Xml,Xslt,我使用的是XSLT2.0 我有以下xml <Test> <Examples> <Example id="uniqueId_1"> <field>test1</field> </Example> <Example id="uniqueId_2"> <field>test2</field> </Example> </Examples>
<Test>
<Examples>
<Example id="uniqueId_1">
<field>test1</field>
</Example>
<Example id="uniqueId_2">
<field>test2</field>
</Example>
</Examples>
<references>
<reference ref="example1">
<value ref="uniqueId_1"/>
</reference>
<reference ref="example2">
<value ref="uniqueId_1"/>
</reference>
</references>
<destinations>
<destination id="example1">
<address> add1 </address>
</destination>
<destination id="example2"/>
</destinations>
</Test>
测试1
测试2
地址1
我需要使用XSLT2.0将其打包成另一个xml
生成的xml应该如下所示
<Fields>
<Field value="test1" address="add1"/>
<Field value="test2" address="" />
</Fields>
因此本质上,对于
示例中的每一行
我必须查看哪个引用
与之匹配,并从中导出目的地
。我对这个循环将如何工作感到非常困惑。我会对每个示例元素的每个进行,但如何将一个示例id与多个引用进行比较,然后对每个引用进行多个目的?您是在用命令式/程序性术语进行思考。XSLT不是这样工作的。在XSLT中,您不编写命令或循环,而是使用规则和谓词描述所需的输出
在这里,您需要一个规则(“模板”)来匹配字段
元素。在所有其他条件相同的情况下,这将为任何字段
元素调用。在它里面,你描述了你想要的输出
现在是我提到的“谓词”的一个例子。可以使用方括号语法过滤/搜索元素[]
。/
符号以整个文档中的所有引用开始(我们也可以编写/Test/references
)。然后我们得到他们所有的reference
子项,然后用方括号选择那些value
child的ref
属性与我们上面计算的字段id
匹配的子项
<!-- find reference elt whose "value" child's ref attribute matches -->
<xsl:variable name="reference"
select="//references/reference[value/@ref = $field_id]"/>
<!-- find the destination whose id matches the reference's ref -->
<xsl:variable name="destination"
select="//destinations/destination[@id = $reference/@ref"/>
<!-- pull destination's address and set as value of 'address' att -->
<xsl:value-of select="$destination/address"/>
</xsl:attribute>
</Field>
</xsl:template>
可以通过使用XSL特性(如XSL:key
)预先构建映射来优化上述内容,但我们将把它留到下次使用
关于XSLT的说明
了解XSLT需要一些时间。如果您发现自己对每个
都使用了,或者在XSLT中使用了如果
或者选择了
,那么您可能做错了什么。可以说循环和条件逻辑内置于XSLT中;它是为你做的。或者更准确地说,这是它的谋生之道,是它存在的理由。如果您希望以这种方式查看输入元素,则规则“循环”输入元素,并处理应用的元素。诸如foo[@id='id']
之类的谓词“循环”子级,并查找那些匹配其id等于id
的条件的子级 “对于示例中的每一行,我必须查看哪个引用与之匹配,并从中导出目的地”您确定吗?看起来一个示例可以引用到多个目的地,反之亦然,因此正确的处理方法是为每个引用生成一个字段。
<xsl:template match="/">
<Fields>
<xsl:apply-children/>
</Fields>
</xsl:template>