gpt4 book ai didi

ruby-on-rails - 如何使用 Nokogiri 验证 XML?

转载 作者:太空宇宙 更新时间:2023-11-03 18:10:48 24 4
gpt4 key购买 nike

我必须验证 XML 文档,这样它就不会接受无效的 XML 文档。

我这样做是为了处理无效文档:

xml ||= Nokogiri::XML xml_data do |config| 
config.strict
end
rescue Nokogiri::XML::SyntaxError => e
puts "caught exception: #{e}"
else
#further processing if no error

但即使对于有效的 XML 文档,它也会显示:

caught exception: Extra content at the end of the document

我正在使用的示例 XML:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE note SYSTEM "Note.dtd">
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

我做错了什么?

最佳答案

如果要查看文档是否为无效 XML,只需检查返回文档的 errors 方法即可:

require 'nokogiri'

doc = Nokogiri::XML('<xml><foo></xml>')
doc.errors
# => [#<Nokogiri::XML::SyntaxError: Opening and ending tag mismatch: foo line 1 and xml>,
# #<Nokogiri::XML::SyntaxError: Premature end of data in tag xml line 1>]

如果 Nokogiri 发现任何错误,它将填充 errors 数组。

关于ruby-on-rails - 如何使用 Nokogiri 验证 XML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34594065/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com