我从CSS验证服务中获得了XML响应,看起来像这样:
{vextwarning=false, output=soap12, lang=en, warning=2, medium=all, profile=css3}
<?xml version='1.0' encoding="utf-8"?>
<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope">
<env:Body>
<m:cssvalidationresponse
env:encodingStyle="http://www.w3.org/2003/05/soap-encoding"
xmlns:m="http://www.w3.org/2005/07/css-validator">
<m:uri>file:tmp.css</m:uri>
<m:checkedby>http://jigsaw.w3.org/css-validator/</m:checkedby>
<m:csslevel>css3</m:csslevel>
<m:date>2014-01-28T09:33:32Z</m:date>
<m:validity>false</m:validity>
<m:result>
<m:errors xml:lang="en">
<m:errorcount>1</m:errorcount>
<m:errorlist>
<m:uri>file:tmp.css</m:uri>
<m:error>
<m:line>1</m:line>
<m:errortype>parse-error</m:errortype>
<m:context> asdf321 </m:context>
<m:errorsubtype>
exp
</m:errorsubtype>
<m:skippedstring>
123
</m:skippedstring>
<m:message>
Property bla doesn't exist :
</m:message>
</m:error>
</m:errorlist>
</m:errors>
<m:warnings xml:lang="en">
<m:warningcount>0</m:warningcount>
</m:warnings>
</m:result>
</m:cssvalidationresponse>
</env:Body>
</env:Envelope>
我想使用诺科吉里(Nokogiri)对其进行解析,但我完全陷入困境。我知道如何使用Nokogiri解析CSS和东西,但是XML对我来说是很新的。
例如,我想获得m:validity
的值,或者我想在m:errors
上迭代。请给我一些有关如何做到这一点的小提示。非常感谢。
看起来您正在处理肥皂消息,因此我建议您使用soap库作为ruby,例如savon。
但是,如果您是从另一个来源获取XML文档,则可以使用名称为XPath的查询来解析它:
class CssValidationResponse
attr_reader :valid, :errors
def initialize(xml)
doc = Nokogiri::XML(xml)
xmlns = { 'm' => 'http://www.w3.org/2005/07/css-validator' }
@valid = (doc.xpath('//m:validity', xmlns).text == 'true')
@errors = doc.xpath('//m:error/m:message', xmlns).map { |n| n.text.strip }
end
end
xml = read_my_xml_file
validator = CssValidationResponse.new(xml)
validator.valid # => false
validator.errors # => ["Property bla doesn't exist :"]