使用XSLT将嵌套XML结构转换为扁平XML结构
我正在XSLT中尝试这个任务:将包含嵌套元素的XML转换为嵌套较少的XML格式 转换自:使用XSLT将嵌套XML结构转换为扁平XML结构,xml,xslt,Xml,Xslt,我正在XSLT中尝试这个任务:将包含嵌套元素的XML转换为嵌套较少的XML格式 转换自: <example> <value> aaa <value> bbb <value> ccc </value> </value> </value> </example> aaa bbb ccc 致: aaa aaa bbb bbb ccc c
<example>
<value>
aaa
<value>
bbb
<value>
ccc
</value>
</value>
</value>
</example>
aaa
bbb
ccc
致:
aaa
aaa
bbb
bbb
ccc
ccc
我一直在努力寻找解决方案,但我只有一个:
<xsl:template match="/">
<exmaple>
<xsl:apply-templates/>
</exmaple>
</xsl:template>
<xsl:template match="//value/text()">
<value><xsl:value-of select="."/></value>
<value><xsl:value-of select="."/></value>
</xsl:template>
结果(空标记的问题):
aaa
aaa
bbb
bbb
ccc
ccc
使用XPath//value/text()[1]
尝试此模板:
<xsl:template match="//value/text()[1]">
<value><xsl:value-of select="." /></value>
<value><xsl:value-of select="." /></value>
</xsl:template>
诀窍是您需要从每个
中选择第一个文本节点,因为text()
将返回它们的集合。
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:output indent="yes"/>
<xsl:template match="example">
<xsl:copy>
<xsl:apply-templates select=".//value"/>
</xsl:copy>
</xsl:template>
<xsl:template match="value">
<xsl:copy>
<xsl:value-of select="normalize-space(text())"/>
</xsl:copy>
<xsl:copy>
<xsl:value-of select="normalize-space(text())"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
<xsl:template match="//value/text()[1]">
<value><xsl:value-of select="." /></value>
<value><xsl:value-of select="." /></value>
</xsl:template>
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:output indent="yes"/>
<xsl:template match="example">
<xsl:copy>
<xsl:apply-templates select=".//value"/>
</xsl:copy>
</xsl:template>
<xsl:template match="value">
<xsl:copy>
<xsl:value-of select="normalize-space(text())"/>
</xsl:copy>
<xsl:copy>
<xsl:value-of select="normalize-space(text())"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>