我有一个类似于此的XML源:
<?xml version="1.0" encoding="utf-8"?>
<records>
<record>
<employee>
<firstname>Tom</firstname>
<lastname>Hanks</lastname>
</employee>
<boss firstname="Sylvester" lastname="Stallone">Sylvester</boss>
</record>
<record>
<employee>
<firstname>Tom</firstname>
<lastname>Hanks</lastname>
</employee>
<boss firstname="Johnny" lastname="Depp">Johnny</boss>
</record>
<record>
<employee>
<firstname>Johnny</firstname>
<lastname>Depp</lastname>
</employee>
<boss firstname="Robin" lastname="Williams">Robin</boss>
</record>
</records>并希望将所有的名字合并到一个单独的列表中,以便能够打印如下内容:
<root>
<firstname>Tom</firstname>
<firstname>Sylvester</firstname>
<firstname>Johnny</firstname>
<firstname>Robin</firstname>
</root>我做了一些测试,终于能够使用这个XSLT将所有内容合并到一个字符串中:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:template match="/">
<root>
<xsl:variable name="all_Users" select="records/record/employee/firstname" />
<xsl:variable name="all_Values" select="records/record/boss" />
<xsl:variable name="all_first_names" >
<xsl:copy-of select="$all_Users"/>
<xsl:copy-of select="$all_Values"/>
</xsl:variable>
<xsl:for-each select="$all_first_names">
<firstname><xsl:value-of select="." /></firstname>
</xsl:for-each>
</root>
</xsl:template>
</xsl:stylesheet>以下是我的结果:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<firstname>TomTomJohnnySylvesterJohnnyRobin</firstname>
</root>有没有办法将序列$all_Users和$all_Values合并成一个序列,而不是一个字符串?
先谢谢你。
发布于 2020-02-24 18:52:28
为什么不简单地:
XSLT2.0
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="/records">
<root>
<xsl:for-each select="distinct-values(record/employee/firstname | record/boss/@firstname)">
<firstname>
<xsl:value-of select="." />
</firstname>
</xsl:for-each>
</root>
</xsl:template>
</xsl:stylesheet>Demo:https://xsltfiddle.liberty-development.net/6rexjij
你的尝试的主要问题(除了没有处理不同的要求)是:
<xsl:for-each select="$all_first_names">只有一个all_first_names变量。如果要为其每个节点创建一个元素,则需要执行以下操作:
<xsl:for-each select="$all_first_names/node()">https://stackoverflow.com/questions/60382066
复制相似问题