gpt4 book ai didi

ruby - 我如何使用 nokogiri 验证 XHTML?

转载 作者:数据小太阳 更新时间:2023-10-29 06:41:32 26 4
gpt4 key购买 nike

我发现一些帖子暗示您可以使用 nokogiri gem 根据其 DTD 验证 XHTML。虽然我已经成功地使用它来解析 XHTML(寻找“a”标签等),但我正在努力验证文档。

对我来说,这是:

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

结果是:

[
#<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.]
]

所以我假设这不是正确的方法。我似乎找不到任何好的例子 - 谁能指出我做错了什么?

我在 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

最佳答案

不仅仅是你。你正在做的应该是正确的方法,但我从来没有运气。据我所知,Nokogiri 和 libxml 之间存在某种断开连接,导致它无法加载 SYSTEM DTD,或无法识别 PUBLIC DTD。如果您在 XML 文件中定义 DTD,它起作用,但祝您使用 XHTML DTD 做到这一点。

我可以推荐的最好的方法是使用 schemas for 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) # => []

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

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