使用XSLT以字符串替换形式将修订应用于HTML文档

问题描述 投票:0回答:2

我需要编辑大量的HTML(可能还有其他xml)文档。

编辑部分通常采用“ John Doe”->“ [Person A]”的形式。要编辑的文本可能在标题或段落中,但几乎总是在段落中。

真的是简单的字符串替换。不是很复杂的事情。

但是,我确实希望保留文档结构,并且我不想重塑任何轮子。文档文本中的字符串替换可以完成此工作,但也可能破坏文档结构,因此这将是最后的选择。

现在,我已经盯着XSLT呆了一个小时,并试图迫使“ str:replace”进行我的出价。我会避免让您看不见没有效果的微不足道的尝试,但是我会问:是否有一种简单明了的方法来使用XSLT应用我的修订,您可以在此处发布吗?

先谢谢您。

更新:应Martin Honnen的请求,我正在添加输入文件以及用于获取最新错误消息的命令。由此看来,当涉及到XSLT时,我是一个完整的n00b:-)

。html文件:

今天的日期 title><meta name="“" created content="“"> head><ol start="“"><li> <p>约翰·杜(John Doe)9月fux 2057和亨利(Henry)Fluebottom成立了Doe&;公司。 Fluebottom小部件公司 p> ol> body> html></p></li></ol>

XSLT转换文件:

<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
        xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
        >
<xsl:template match="p">
  <xsl:copy>
<xsl:attribute name="matchesPattern">
  <xsl:copy-of select='str:replace("John Doe", ".*",  "[Person A]")'/>
</xsl:attribute>
  <xsl:copy-of select='str:replace("Henry Fluebottom", ".*",  "[Person B]")'/>
  </xsl:copy>
</xsl:template>
</xsl:stylesheet>

命令和输出:

$  xsltproc -html transform.xsl example.html
xmlXPathCompOpEval: function replace bound to undefined prefix str
xmlXPathCompiledEval: 2 objects left on the stack.
<?xml version="1.0"?>



    TodaysDate




      <p matchesPattern=""/>  

$ 
html xml xslt transformation redaction
2个回答
0
投票

第一个问题是找到一个实际上支持字符串替换的XSLT处理器。 replace()函数在XSLT 2.0+中是标准的,但在XSLT 1.0中不存在。某些XSLT 1.0处理器在其他名称空间中支持扩展功能str:replace(),但至少,您需要在样式表中添加名称空间声明xmlns:str="http://exslt.org/strings"才能找到该功能。我不知道这是否行得通(我不知道是否可以通过xsltproc使用此功能)。我的建议是改用XSLT 2.0+处理器。

下一个问题是您调用该函数的方式。通常,正确的调用将是

replace(., "John Doe", "[Person A]")

尽管您将不得不跳几圈,才能在同一字符串上进行多次替换。

我不知道您想通过<xsl:attribute name="matchesPattern">指令实现什么。


0
投票

xsltproc基于libxslt,并且该方式支持各种EXSLT函数,例如str:replace,要使用它,您需要声明名称空间

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:str="http://exslt.org/strings"
    exclude-result-prefixes="str"
    version="1.0">

    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="p//text()">
        <xsl:value-of select="str:replace(., 'John Doe', '[Person A]')"/>
    </xsl:template>

</xsl:stylesheet>
© www.soinside.com 2019 - 2024. All rights reserved.