如何使用 Nokogiri 验证 XML?
How to validate XML using Nokogiri?
我必须验证 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
数组。
我必须验证 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
数组。