输入XML:
<?xml version="1.0" encoding="UTF-8"?>
<Root>
<Entry>
<Tag1>A1</Tag1>
<Tag2>B1</Tag2>
</Entry>
<Entry>
<Tag1>A2</Tag1>
<Tag2/>
</Entry>
</Root>
XSLT:
<?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="3.0">
<xsl:output method="text"/>
<xsl:mode on-no-match="shallow-skip" streamable="yes" use-accumulators="#all"/>
<xsl:accumulator name="Tag2" as="xs:string"
initial-value="''" streamable="yes">
<xsl:accumulator-rule match="Tag2/text()"
select="." />
</xsl:accumulator>
<xsl:template match="/*" expand-text="yes">
<xsl:apply-templates/>
Tag2 {accumulator-after('Tag2')}
</xsl:template>
</xsl:stylesheet>
输出:
Tag2 B1
我期望输出为 Tag2
<<empty>>
,因为第二个元素没有针对 Tag2 定义的值。
我们是否可以检查并确保累加器考虑节点没有值的情况?
在text()节点上匹配,空元素中没有文本节点。
添加与将值设置为空字符串的元素匹配的规则:
<xsl:accumulator name="Tag2" as="xs:string"
initial-value="''" streamable="yes">
<xsl:accumulator-rule match="Tag" select="''"/>
<xsl:accumulator-rule match="Tag2/text()"
select="." />
</xsl:accumulator>