【问题标题】:Removing all HTML inside XML删除 XML 中的所有 HTML
【发布时间】:2013-07-26 05:01:58
【问题描述】:

我正在尝试将一些 XML 提供给 Apache Solr,但是一些 XML 在文本中包含一些 HTML 格式,这不会让我发布到我的 solr 服务器。显然,能够保留这些信息会很好,因为我的文档可以在发布之前进行预格式化。但是我没有看到或不知道转义是否会避免 solr 的 HTML 问题。我的问题很热门,我是否使用 XSLT 从 XML 中删除 HTML?

例如:

What I have:

<field name="description"><h1>This is a description of a doc!</h1><p> This doc contains some information</p></field>

What I need:

<field name="description">This is a description of a doc! This doc contains some information.</field>

我想要一个智能修复,而不是在 xsl 翻译期间不清理的特定标签的黑名单。这将是低效的,因为如果决定创建一个带有say标签的新文档,黑名单将不会看到这一点,除非程序员手动添加它。

我尝试将 HTML 标记转换为 html 实体(),但是当我尝试通过 BasicNameValuePairs 通过 HtmlPost 发布此内容时,这会搞砸事情。我不想使用这些实体。

对 StackOverflow 有什么想法吗?

【问题讨论】:

    标签: xml xslt solr html-entities


    【解决方案1】:

    如果您知道包含 HTML 的元素,您可以匹配任何这些元素的后代并执行应用模板。

    示例...

    XML 输入

    <field name="description"><h1>This is a <b>description</b> of a doc!</h1><!--Here's a comment--><p> This doc contains some information</p></field>
    

    XSLT 1.0

    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
        <xsl:output method="xml" indent="yes"/>
    
        <xsl:template match="node()|@*">
            <xsl:copy>
                <xsl:apply-templates select="node()|@*"/>
            </xsl:copy>
        </xsl:template>
    
        <xsl:template match="node()[ancestor::field and not(self::text())]">
            <xsl:apply-templates/>
        </xsl:template>
    
    </xsl:stylesheet>
    

    XML 输出

    <field name="description">This is a description of a doc! This doc contains some information</field>
    

    【讨论】:

    • 但这不会摆脱 HTML 注释,例如 所以它并不像我想要的那样智能。看到了吗?
    • @BenjaminNeigher - 您可以将匹配更改为 node()[ancestor::field and not(self::text())]
    • @BenjaminNeigher - 我更新了我的示例以显示 cmets 也被删除。
    • 谢谢丹尼尔!这样就可以了
    猜你喜欢
    • 1970-01-01
    • 2016-02-18
    • 2011-11-08
    • 2016-06-01
    • 2011-07-31
    • 2016-04-06
    • 2012-03-16
    • 2012-01-07
    • 2020-08-30
    相关资源
    最近更新 更多