【问题标题】:Invalid bell character inside XML tag using Nokogiri使用 Nokogiri 的 XML 标记内的铃铛字符无效
【发布时间】:2015-10-29 20:36:12
【问题描述】:

我正在使用Nokogiri::XML::SAX::Document 来解析一个由购物元素填充的 XML 文件。

其中一些项目的段落中带有铃铛字符,但没有 CDATA 块部分:

<description>Amazing product that will blow your mind. ^G Caution: may cause skin irritation and death.</description>

* ^G 是这个字符在 VIM 中的显示方式。

该元素的解析失败,然后我收到以下错误:

XML document contains errors, check this: PCDATA invalid Char value 7.

有没有办法读取上面显示的元素而忽略 Nokogiri 中的无效字符?

【问题讨论】:

  • 如果没有上下文中的 XML 数据和代码示例,真的很难说出问题所在。请参阅“How to Ask”。我们不会编写 SAX 代码,因此我们需要您向我们展示您尝试过的内容。因为它是有效的 XML 标记,所以错误可能发生在 XML 的其他地方,并且正在抛出解析器。
  • 错误信息是指“Char value 7”。字符 7 是一个控制字符(ASCII 中的 Bell character),它在 XML 中无效(至少 1.0)。当我创建包含该字符的示例文档并对其进行解析时,我会收到相同的错误消息。你的问题是这个字符,而不是冒号。

标签: ruby nokogiri


【解决方案1】:

不是无效字符; : 在文本节点中完全有效。问题必须出在其他地方,可能是由于文档中的无效 XML 在解析文档时混淆了 libXML。

require 'nokogiri'

doc = Nokogiri::XML::DocumentFragment.parse('<description>Amazing product that will blow your mind. Caution: may cause skin irritation and death.</description>')
doc.to_xml # => "<description>Amazing product that will blow your mind. Caution: may cause skin irritation and death.</description>"
doc.errors # => []

doc.at('description').text # => "Amazing product that will blow your mind. Caution: may cause skin irritation and death."

要查看您的文档是否有效,请使用 errors 方法让 Nokogiri 返回一组错误。在上面的代码中它返回一个空数组,这意味着解析的内容没有问题。


...我发现了真正导致问题的角色...

<description>Amazing product that will blow your mind. ^G Caution: may cause skin irritation and death.</description>

您可以使用trdelete 在解析之前删除不需要的字符。不要在搜索字符串中使用^G,而是使用\a,因为它的值相同,只是更容易处理:

>> "^G".ord#=> 7
>> "\a".ord #=> 7

所以,你可以这样做:

require 'nokogiri'

xml = "<description>Amazing product that will blow your mind. \a Caution: may cause skin irritation and death.</description>"
doc = Nokogiri::XML::DocumentFragment.parse(xml.delete("\a"))
doc.to_xml # => "<description>Amazing product that will blow your mind.  Caution: may cause skin irritation and death.</description>"

【讨论】:

  • 在重新调查情况后,我发现了真正导致问题的角色,并编辑了问题
  • 有时我们会看到损坏的标记,无论是 XML 还是 HTML。在 HTML 中,它并不像一个非常宽松的标准那么重要。 XML 更加挑剔。当我们遇到这样的问题时,通常最好进行飞行前检查并在解析之前修复我们知道存在的问题。我将添加一个我会做什么的示例。
  • 我不确定如何使用 SAX 解析器来做到这一点,但你已经帮了我很多。
  • 您可能必须在命令行中使用sed 来预处理文件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-20
  • 2012-05-15
  • 1970-01-01
  • 2017-08-11
  • 1970-01-01
相关资源
最近更新 更多