我有一个包含几个大部分类似数据的xml。我希望能够根据优先级列表选择一个部分,以及该部分是否存在。
例如,如果A部分存在,则仅使用A,如果它不存在则使用B等,但仅使用它找到的第一部分,基于我设置的优先级而不是xml中的顺序。
到目前为止,这是xsl:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
exclude-result-prefixes="xs"
version="2.0">
<xsl:template match="/">
<xsl:apply-templates select="sources/source"></xsl:apply-templates>
</xsl:template>
<xsl:template match="source">
<xsl:choose>
<xsl:when test="@type='C' or @type='B' or @type='A'">
<xsl:value-of select="name"/>
<xsl:value-of select="age"/>
</xsl:when>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
这是xml exmple:
<?xml version="1.0" encoding="UTF-8"?>
<sources>
<source type='C'>
<name>Joe</name>
<age>10</age>
</source>
<source type='B'>
<name>Mark</name>
<age>20</age>
</source>
<source type='A'>
<name>David</name>
<age>30</age>
</source>
</sources>
所以我在这里要说的是C是我的第一选择,然后是B然后A。
答案 0 :(得分:2)
只需按优先顺序选择序列,然后使用序列中的第一项......
XSLT 2.0
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:strip-space elements="*"/>
<xsl:template match="/">
<xsl:apply-templates select="(sources/source[@type='C'],
sources/source[@type='B'],
sources/source[@type='A'])[1]"/>
</xsl:template>
<xsl:template match="source">
<xsl:value-of select="name,age" separator=" - "/>
</xsl:template>
</xsl:stylesheet>
<强>输出强>
Joe - 10
注意:我更改了source
的覆盖仅用于演示目的。