如何从XML文件中删除带有样式属性的DIV标记?

时间:2012-04-25 00:20:40

标签: xml regex

我有一个巨大的Wordpress XML导出。不幸的是,一些混蛋设法将代码注入到安装中并将DIV注入到内容中。 现在我想清理那个烂摊子。这是它的样子:

<p>Normal Text</p>
<div style="position:absolute;top:-9660px;left:-4170px;"><a href="http://insane.link.com">Insane Linktext</a></div>
<div style="position:absolute;top:-2460px;left:-5370px;"><a href="http://insane.link.com">Another Insane Linktext</a></div>
<p>Normal good people's brains' text</p>

我考虑过使用一些正则表达式来匹配包含STYLE属性的DIV。可用的工具是Aptana或其他TextEditors和PHP服务器以及OSX终端。有什么建议吗?

谢谢,干杯!

3 个答案:

答案 0 :(得分:2)

我建议不要使用正则表达式,而是使用真正的XML解析器。例如,由于您使用的是OS X,因此已经安装了Ruby,您可以使用以下方法清理HTML:

require 'nokogiri'                      # Use `sudo gem install nokogiri` first
html = Nokogiri.HTML(IO.read(ARGV[0]))  # read and parse the HTML document
html.css('div[style]').remove           # destroy all <div style="...">...</div>
File.open(ARGV[1],'w'){ |f| f << html } # write the html to disk as a new file

根据评论,您首先需要安装Nokogiri。

然后,将上面保存为“clean_divs.rb”,然后键入ruby clean_divs.rb my.html my_fixed.html(其中第一个是要读取的文件的名称,第二个是要写入的文件的名称)。

如果您希望在销毁过程中更精确,可以使用XPath选择要销毁的元素,例如: html.xpath('//div[@style][a]').remove仅查找具有样式属性和<a>直接子元素的div。

答案 1 :(得分:0)

这可能对您有所帮助:它将匹配您在上面提供的div:

<div style="[a-zA-Z0-9-:;]+"><a href="[a-z:/.]+">[a-zA-Z ]+</a></div>

但是,它只会匹配div > a > text模式,而只会匹配具有样式属性且没有其他内容的div。

您应该可以使用大多数HTML编辑器进行查找和替换(Dreamweaver和Notepad ++都允许)

答案 2 :(得分:0)

您可以将修改后的identity transform<div>元素的空模板一起使用,以便将其删除:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

    <!--default processing for content is to copy forward -->
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <!--remove the rogue div elements -->
    <xsl:template match="div[@style]" />

</xsl:stylesheet>
相关问题