html - 如何知道何时在嵌套元素上放置结束标记

标签 html xml xslt

我正在将以下 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="/">
        &lt;rule&gt;
        <xsl:apply-templates select=".//condition" />
        &lt;/rule&gt;
    </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>
                &lt;condition type="<xsl:value-of select="@type"/>"&gt;<br />
                &lt;/condition&gt;
            </li>
        </ul>
    </xsl:template>
</xsl:stylesheet>

最佳答案

select=".//condition" 具有展平层次结构的效果,因为您将所有级别的所有 condition 元素选择到单个列表中。相反,您需要首先将模板应用于顶级条件:

<xsl:template match="/rule">
    &lt;rule&gt;
    <xsl:apply-templates select="condition" />
    &lt;/rule&gt;
</xsl:template>

然后让 condition 模板通过将模板应用于其自己的子项来处理递归,例如:

<xsl:template match="condition">
    <ul>
        <li>
            &lt;condition type="<xsl:value-of select="@type"/>"&gt;<br />
            <xsl:apply-templates select="condition"/>
            &lt;/condition&gt;
        </li>
    </ul>
</xsl:template>

(我省略了样式部分,一旦您有了使用递归的概念,您就可以在完整的样式表中自行解决 - 事实上,如果您使用填充而不是边距,您可能不需要对祖先的整个计数因为每个 ul 都嵌套在前一个 ul 中)。

关于html - 如何知道何时在嵌套元素上放置结束标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30600660/

相关文章:

c# - 从字符串中剥离 WordML

java - XML:处理大数据

html - 具有水平子导航的响应式下拉菜单

html - CSS不适用于一个类的所有元素

javascript - 将 jquery 动画还原为原始 css 状态

html - 如何在html中使用嵌套的iframe?

android - 在Android中使用drawable中的xml创建像圆弧一样的弯曲线

java - AdMob 横幅 : Not enough space to show ad

c# - 使用 XDocument 获取大写的 UTF-8

python - 如何根据标签之前的标签类别值删除标签?