如何使用nokogiri验证XHTML?

Nei*_*ilS 12 ruby xhtml nokogiri

我发现一些帖子暗示你可以使用nokogiri gem验证XHTML对其DTD的影响.虽然我已成功使用它来成功解析XHTML(寻找'a'标签等),但我正在努力验证文档.

对我来说,这个:

doc = Nokogiri::XML(Net::HTTP.get(URI.parse("http://www.w3.org")))
puts doc.validate
Run Code Online (Sandbox Code Playgroud)

导致整堆:

[
#<Nokogiri::XML::SyntaxError: No declaration for element html>,
#<Nokogiri::XML::SyntaxError: No declaration for attribute xmlns of element html>,
#<Nokogiri::XML::SyntaxError: No declaration for attribute lang of element html>,  
#<Nokogiri::XML::SyntaxError: No declaration for attribute lang of element html>,
#<Nokogiri::XML::SyntaxError: No declaration for element head>,
#<Nokogiri::XML::SyntaxError: No declaration for attribute profile of element head
[repeat for every tag in the document.]
]
Run Code Online (Sandbox Code Playgroud)

所以我假设这不是正确的方法.我似乎无法找到任何好的例子 - 任何人都可以建议我做错了吗?

我在Mac OSX 10.5.8上运行ruby 1.8.6.Nokogiri告诉我:

nokogiri: 1.3.3
warnings: []

libxml: 
  compiled: 2.6.23
  loaded: 2.6.23
  binding: extension
Run Code Online (Sandbox Code Playgroud)

Pes*_*sto 14

这不仅仅是你.你正在做的事情应该是正确的做法,但我从来没有运气好.据我所知,Nokogiri和libxml之间存在一些脱节,导致它无法加载SYSTEMDTD或识别PUBLICDTD.如果您在XML文件中定义DTD ,它将起作用,但是使用XHTML DTD可以做到这一点.

我可以推荐的最好的方法是使用XHTML模式:

require 'nokogiri'
require 'open-uri'

doc = Nokogiri::XML(open('http://www.w3.org'))
xsd = Nokogiri::XML::Schema(open('http://www.w3.org/2002/08/xhtml/xhtml1-strict.xsd'))

#this is a true/false validation
xsd.valid?(doc)    # => true

#this gives a listing of errors
xsd.validate(doc)  # => []
Run Code Online (Sandbox Code Playgroud)