【发布时间】:2018-07-14 14:24:50
【问题描述】:
我是 xml 新手,我很难理解 XSLT 的工作原理。 你能帮我修复我的 xslt 文件中的一些错误吗? 我想转换这个输入文件:
<?xml version="1.0" encoding="utf-8"?>
<data>
<parent><string >AAA</string></parent>
<nb><string >2</string></nb>
<child1>aaa-1</child1>
<child1>aaa-2</child1>
<parent><string >BBB</string></parent>
<nb><string>1</string></nb>
<child2>bbb-1</child2>
<parent><string >CCC</string></parent>
<nb><string >0</string></nb>
</data>
进入:
<?xml version="1.0" encoding="utf-8"?>
<data>
<parent>
<string >AAA</string>
<nb><string >2</string></nb>
<child1>aaa-1</child1>
<child1>aaa-2</child1></parent>
<parent>
<string >BBB</string>
<nb><string >1</string></nb>
<child2>bbb-1</child2></parent>
<parent>
<string >CCC</string>
<nb><string >0</string></nb></parent>
</data>
规则是:
“nb”节点表示每个父节点的子节点数。它可以 为 0。
节点“child1”和“child2”不同。它们很复杂, 带有嵌套循环等。我上面的输入文件为演示而简化。
我 想想,我必须使用“复制”指令。-
对我来说困难的是:
- 对于每个父节点,我必须读取当前父节点之后定义的子节点数(“nb”)
- 当“父”值为“AAA”时,我必须读取“child1”
当“父”值为 !=AAAA 时,我必须读取“childe2”节点。李>
这是我的 XSLT 文件,结果并不完全符合预期:
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
<xsl:template match="/">
<xsl:comment>--- </xsl:comment>
<xsl:comment>1 : parent nodes </xsl:comment>
<xsl:for-each select ="/data/parent">
<p>
<string>
<xsl:value-of select="string"/>
</string>
<xsl:comment>======================= </xsl:comment>
<xsl:comment>2 : nb nodes (how many childs for a parent ) </xsl:comment>
<xsl:for-each select ="/data/nb">
<xsl:if test="((position() < 2) and (normalize-space(position() >= 1)))">
<xsl:comment>Ex. for tThe first value only </xsl:comment>
<xsl:comment>How to do a dynamic test here (expected : AAA->3 (first nb value), BBB->1 (second nb value) ...) ?</xsl:comment>
<xsl:comment>How to synchronise loop on parent and nb ?</xsl:comment>
<nb>
<string>
<xsl:value-of select="string"/>
</string>
</nb>
</xsl:if>
</xsl:for-each>
<xsl:comment>======================= </xsl:comment>
<xsl:comment>3 : child nodes </xsl:comment>
<xsl:comment>How to manage the position and number of nodes to read ?</xsl:comment>
<xsl:comment>Test 'string =AAA' is KO : always child2 </xsl:comment>
<xsl:choose>
<xsl:when test='string =AAA'>
<xsl:copy-of select="/*/child1" />
</xsl:when>
<xsl:otherwise>
<xsl:copy-of select="/*/child2" />
</xsl:otherwise>
</xsl:choose>
</p>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
提前致谢
最好的问候
【问题讨论】:
-
对不起,已经完成了