有谁能帮助我进行以下改造? 这是输入xml: ?xml version="1.0" encoding="UTF-8"?book titleMy book/title pages200/pages sizebig/size author nameSmith/name /author author nameWallace/name /author author nameBrown/name /author/b
这是输入xml:
<?xml version="1.0" encoding="UTF-8"?>
<book>
<title>My book</title>
<pages>200</pages>
<size>big</size>
<author>
<name>Smith</name>
</author>
<author>
<name>Wallace</name>
</author>
<author>
<name>Brown</name>
</author>
</book>
<book>
<title>Other book</title>
<pages>100</pages>
<size>small</size>
<author>King</author>
</book>
<book>
<title>Pretty book</title>
<pages>150</pages>
<size>medium</size>
</book>
这是所需的输出
<book style="even">
<title>My book</title>
<pages>200</pages>
<size>big</size>
<author-name>Smith</author-name>
</book>
<book style="odd">
<title>My book</title>
<pages>200</pages>
<size>big</size>
<author-name>Wallace</author-name>
</book>
<book style="even">
<title>My book</title>
<pages>200</pages>
<size>big</size>
<author-name>Brown</author-name>
</book>
<book style="odd" >
<title>Other book</title>
<pages>100</pages>
<size>small</size>
<author-name>King</author-name>
</book>
<book style="even">
<title>Pretty book</title>
<pages>150</pages>
<size>medium</size>
<author-name />
</book>
我尝试使用xsl:for-each循环,但我想他们让我陷入了死胡同.这里棘手的部分是“风格”属性,无论在任何书中放置了多少作者标签,它都需要“全局”.
此样式表首先存储所有作者节点以及全局变量中没有作者的所有书籍节点. “/”.按文档顺序对它们进行排序.然后主模板迭代此变量中的所有节点,并根据序列中的位置生成输出.<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:variable name="authors" select="(//author | //book[not(author)])/."/>
<xsl:template match="/">
<xsl:element name="result">
<xsl:for-each select="$authors">
<xsl:apply-templates select=".">
<xsl:with-param name="position" select="position()+1"/>
</xsl:apply-templates>
</xsl:for-each>
</xsl:element>
</xsl:template>
<xsl:template match="text()|title|pages|size">
<xsl:copy>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
<xsl:template match="book">
<xsl:param name="position" select="1"/>
<xsl:element name="book">
<xsl:attribute name="style">
<xsl:if test="$position mod 2 = 0">even</xsl:if>
<xsl:if test="$position mod 2 = 1">odd</xsl:if>
</xsl:attribute>
<xsl:apply-templates select="title"/>
<xsl:apply-templates select="pages"/>
<xsl:apply-templates select="size"/>
<xsl:element name="author-name"/>
</xsl:element>
</xsl:template>
<xsl:template match="author">
<xsl:param name="position" select="1"/>
<xsl:element name="book">
<xsl:attribute name="style">
<xsl:if test="$position mod 2 = 0">even</xsl:if>
<xsl:if test="$position mod 2 = 1">odd</xsl:if>
</xsl:attribute>
<xsl:apply-templates select="../title"/>
<xsl:apply-templates select="../pages"/>
<xsl:apply-templates select="../size"/>
<xsl:element name="author-name">
<xsl:if test="name">
<xsl:value-of select="name"/>
</xsl:if>
<xsl:if test="not(name)">
<xsl:value-of select="."/>
</xsl:if>
</xsl:element>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
