我正在将以下 xml 转换为 html:
<rule>
<condition type="AND">
<condition type="AND">
<condition type="NOT">
</condition>
</condition>
</condition>
</rule>
从这个结构中,您可以推断一个条件可以有其他条件(或者不像最后一个条件)。
我试图在 html 中制作相同的结构,但不确定何时/如何/在哪里放置内部有条件的条件的结束标记。这是我当前得到的输出,但我希望它与上面的输出相同:
<rule>
<condition type="AND">
</condition>
<condition type="AND">
</condition>
<condition type="NOT">
</condition>
</rule>
这是我的 xsl:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" />
<xsl:template match="/">
<rule>
<xsl:apply-templates select=".//condition" />
</rule>
</xsl:template>
<xsl:template match="condition">
<xsl:variable name="margin-left"><xsl:number value="(count(ancestor::condition) + 1) * 20" />px</xsl:variable>
<ul class="list-unstyled" style="margin:0px;margin-left:{$margin-left}">
<li>
<condition type="<xsl:value-of select="@type"/>"><br />
</condition>
</li>
</ul>
</xsl:template>
</xsl:stylesheet>
最佳答案
select=".//condition"
具有展平层次结构的效果,因为您将所有级别的所有 condition
元素选择到单个列表中。相反,您需要首先将模板应用于顶级条件
:
<xsl:template match="/rule">
<rule>
<xsl:apply-templates select="condition" />
</rule>
</xsl:template>
然后让 condition
模板通过将模板应用于其自己的子项来处理递归,例如:
<xsl:template match="condition">
<ul>
<li>
<condition type="<xsl:value-of select="@type"/>"><br />
<xsl:apply-templates select="condition"/>
</condition>
</li>
</ul>
</xsl:template>
(我省略了样式部分,一旦您有了使用递归的概念,您就可以在完整的样式表中自行解决 - 事实上,如果您使用填充而不是边距,您可能不需要对祖先的整个计数因为每个 ul
都嵌套在前一个 ul
中)。
关于html - 如何知道何时在嵌套元素上放置结束标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30600660/