我一直试图在一些HTML片段上运行一些处理,在使用Nokogiri时,我遇到了一个我似乎无法理解的问题。
我使用的是以下代码:
doc = Nokogiri::HTML::fragment xml
doc.search("//text()[contains(.,'#{@wordbefore}')]").each do |node|
node.replace(node.content.gsub(/#{@wordbefore}/, ''))
end使用该代码,将跳过整个代码块。但是,如果我使用:
doc = Nokogiri::XML xml它确实有效。我一直在尝试弄清楚为什么会这样,为什么不能这样做,因为我实际上是在传递代码片段,并且我并不希望对内部元素或每个片段上的XML命名空间进行编码,所以我真的希望将它保留为HTML::fragment。但是不能确定这是我遇到的一个bug,还是我做错了什么。
更新:下面是我在scratch中设置的全部测试内容。还有一个注意事项。我意识到这将扼杀术语元素中的内容。在现实中,这部分并不存在,因为它在不同的阶段发生了变化,但对我来说,这是获取真实内容的最简单方法。
xml = <<-EOXML
<p dir="ltr" class="FM_Body">The Cortex-A5 MPCore processor is a high-performance, low-power, ARM macrocell with an L1 cache subsystem that provides full virtual memory capabilities. Up to four individual cores can be linked in a cache-coherent cluster, under the control of a <term>Snoop Control Unit</term> (SCU), that maintains L1 data cache coherency for memory marked as shared. The Cortex-A5 MPCore processor implements the ARMv7 architecture and runs 32-bit ARM instructions, 16-bit and 32-bit Thumb instructions, and 8-bit Java<tm tmtype="tm">Java</tm> bytecodes in Jazelle state.</p>
EOXML
doc = Nokogiri::XML xml
@wordbefore = "Java"
doc.search("//text()[contains(.,'#{@wordbefore}')]").each do |node|
node.replace(node.content.gsub(/#{@wordbefore}/, ''))
end
p doc.to_xml发布于 2020-04-25 02:26:16
维护Nokogiri的人给我回了信。事实证明,这是HTML片段和Xpath搜索的一个已知问题。在我的特殊情况下,解决方案是通过.//text()而不仅仅是//text()向上爬树。
https://stackoverflow.com/questions/61411877
复制相似问题