输入(我编辑了输入和输出以便更好地理解)
<csv>
<row>
<id>a</id>
<more>1</more>
<stuff>123</stuff>
<row>
<id>1345</id>
<stuff>dga</stuff>
</row>
<row>
<id>68968</id>
<stuff>jkjh</stuff>
</row
</row>
<row>
<id>b</id>
<more>12</more>
<stuff>asdf</stuff>
<row>
<id>abhz</id>
<stuff>ghjk</stuff>
</row>
</row>
</csv>期望输出
<csv>
<bamboo id="a" more="1">
<p>123</p>
</bamboo>
<bamboo id="1345">
<p>dga</p>
</bamboo>
<bamboo id="68968>
<p>jkjh</p>
<bamboo id="b" more="12">
<p>asdf</p>
</bamboo>
<bamboo id="abhz">
<pghjk</p>
</bamboo>
</csv>我的尝试:
<?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="1.0">
<xsl:template match="csv">
<somelementshere>
<text>
<body>
<div type="bamboopower">
<xsl:apply-templates select="@* | node()"/>
</div>
</body>
</text>
</somelementshere>
</xsl:template>
<xsl:template match="row">
<bamboo id="{id}" more="{1}">
<p><xsl:value-of select="stuff"/></p>
</bamboo>
<bamboo id="row/row[comment_id]">
<p><xsl:value-of select="row/row/stuff"/></p>
</bamboo>
</xsl:template>
</xsl:stylesheet>我的输出看起来是:
<bamboo id="a" more="1">
<p>123</p>
</bamboo>
<bamboo id="">
<p/>
</bamboo>
<bamboo id="b" more="12">
<p>123</p>
</bamboo>
<bamboo id="">
<p/>
</bamboo>正如您所看到的,行/行的内容丢失了。我做错了什么?此外,他也不执行贯穿所有行/行的操作。行中可以有多个子行,我需要所有的子行。
(我需要更多的细节,我的帖子主要由代码组成。)
发布于 2018-06-12 13:08:02
你有一个问题就是这个表情..。
<xsl:value-of select="row/row/stuff"/>您目前正在匹配一个row元素,因此您的表达式将相对于该元素,因此通过执行row/row,您将查找名为row的"grand-child“元素。你真的做了<xsl:value-of select="row/stuff"/>
对于为第二个id创建bamboo属性来说,这也是类似的。应该是这样的(我已经将comment_id替换为id,因为您的XML中没有comment_id )
<bamboo id="{row/id}">第二个问题是,代码只假定一个子row元素,其中可能有多个。对于创建第二个bamboo和后续xsl:for-each,您应该将其包装在一个xsl:for-each中。
试试这个XSLT
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" indent="yes" />
<xsl:template match="csv">
<div type="bamboopower">
<xsl:apply-templates select="@* | node()"/>
</div>
</xsl:template>
<xsl:template match="row">
<bamboo id="{id}" more="{more}">
<p><xsl:value-of select="stuff"/></p>
</bamboo>
<xsl:for-each select="row">
<bamboo id="{id}">
<p><xsl:value-of select="stuff"/></p>
</bamboo>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>或者,您可以采用这种方法来删除一些重复的编码:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" indent="yes" />
<xsl:template match="csv">
<div type="bamboopower">
<xsl:apply-templates select="//row"/>
</div>
</xsl:template>
<xsl:template match="row">
<bamboo id="{id}">
<xsl:if test="more">
<xsl:attribute name="more">
<xsl:value-of select="more" />
</xsl:attribute>
</xsl:if>
<p><xsl:value-of select="stuff"/></p>
</bamboo>
</xsl:template>
</xsl:stylesheet>https://stackoverflow.com/questions/50817753
复制相似问题