用Nokogiri解析XML文件?
问题描述:
<DataSet xmlns="http://www.atcomp.cz/webservices">
<xs:schema xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" id="file_mame">...</xs:schema>
<diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1">
<alldata xmlns="">
<category diffgr:id="category1" msdata:rowOrder="0">
<category_code>P.../category_code>
<category_name>...</category_name>
<subcategory diffgr:id="subcategory1" msdata:rowOrder="0">
<category_code>...</category_code>
<subcategory_code>...</subcategory_code>
<subcategory_name>...</subcategory_name>
</subcategory>
....
如何获取所有categories
和subcategories
的数据?用Nokogiri解析XML文件?
我想是这样的:
reader.xpath('//DataSet/diffgr:diffgram/alldata').each do |node|
但是这给了我:
undefined method `xpath' for #<Nokogiri::XML::Reader:0x000001021d1750>
答
引入nokogiri的Reader分析器不支持的XPath。请尝试使用Nokogiri的内存中的Document解析器。
在另一方面,查询xpath命名空间,您需要提供一个命名空间映射,像这样:
doc = Nokogiri::XML(my_document_string_or_io)
namespaces = {
'default' => 'http://www.atcomp.cz/webservices',
'diffgr' => 'urn:schemas-microsoft-com:xml-diffgram-v1'
}
doc.xpath('//default:DataSet/diffgr:diffgram/alldata', namespaces).each do |node|
# ...
end
或者你可以remove the namespaces:
doc.remove_namespaces!
doc.xpath('//DataSet/diffgram/alldata').each { |node| }
感谢你回答约翰,但不幸的是,脚本不进入循环=>所以解析不会开始 – user984621 2012-07-17 19:12:05
此外,我只是试图打印出'put doc',结果只是''' ,这很奇怪 – user984621 2012-07-17 19:22:13
它听起来像你的'my_ document_string_or_io'是空的 – 2012-07-17 21:34:21