【问题标题】:Remove empty tags from XML via XSLT and bubble elements up通过 XSLT 从 XML 中删除空标签并向上冒泡元素
【发布时间】:2017-10-16 16:06:44
【问题描述】:

我有以下问题。 我有一个这样的 xml 文件

<p>
    <span class="dateline">City</span><p>
        <p>
            <em>City.</em>some text
        </p>
    </p><p>
        <p/>
    </p>
    [... unknown number of other nested paragraphs with text ...]
</p>

我希望它看起来像这样:

<p>
    <span class="dateline">City</span>
    <em>City.</em>some text
</p>

因此,只要有父 p-tag,我就必须转到每个叶子 p-tag 并获取其中的所有内容并将其移动到父 p-tag。 之后我会删除所有空的 p-tags。

xslt 1.0 如何做到这一点?

【问题讨论】:

  • 除了手动编辑,你还尝试过什么?请张贴代码。
  • 欢迎来到 Stack Overflow。如果您以允许其他人重现问题的形式展示您尝试过的方法,您更有可能在此处获得对问题的良好回答(如果您不知道从哪里开始,这当然很困难)。不展示你的作品给人的印象是你什么都没做过,只是想让别人为你做你的工作。在 SO help files 和 Eric Raymond 和 Rick Moen 的文章 How to ask questions the smart way 中提出了关于提出有效问题的好建议。

标签: xml xslt


【解决方案1】:

我会写一个身份转换(如果你不知道那是什么,请查看它,因为它值得学习),然后为段落添加两个模板:一个带有 match="p" 以匹配 p 元素不嵌套在其他 p 元素中,并且一个与 match="p[ancestor::p]" 匹配以匹配其他元素。第一个模板只是对标识模板的明确重述(也就是说,可以在不改变功能的情况下省略模板;我将其包括在内只是为了明确处理所有段落)。第二个省略了xsl:copy 指令,只是将模板应用于所有子项。

【讨论】:

  • 教学完美。
【解决方案2】:
<!-- This template preserve all elements without template -->   

<xsl:template match="*">
    <xsl:copy>
        <xsl:copy-of select="@*"/>
        <xsl:apply-templates />
    </xsl:copy>
</xsl:template>


<!-- This template remove all elements without childs (you can replace * by p)-->
<xsl:template match="*[not(node())]"/>
<!-- This template remove p inside other p but preserve all childs --> 
<xsl:template match="p[parent::p]">
    <xsl:apply-templates />
</xsl:template>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-06
    • 2016-06-13
    • 2021-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多