【问题标题】:Parsing an XML file with Nokogiri?Parsing an XML file with Nokogiri?
【发布时间】:2012-07-16 17:18:35
【问题描述】:
<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>
....

如何获取所有categoriessubcategories 数据?

我正在尝试类似的东西:

reader.xpath('//DataSet/diffgr:diffgram/alldata').each do |node|

但这给了我:

undefined method `xpath' for #<Nokogiri::XML::Reader:0x000001021d1750>

【问题讨论】:

    标签: ruby xml xml-parsing nokogiri


    【解决方案1】:

    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|  }
    

    【讨论】:

    • 谢谢你回答约翰,但不幸的是,脚本没有进入循环 => 所以解析没有开始
    • 还有,我刚刚尝试打印出put doc,结果只有&lt;?xml version="1.0"?&gt;,很奇怪
    • 听起来你的my_document_string_or_io 是空的
    猜你喜欢
    • 2013-07-10
    • 2016-09-25
    • 2014-05-20
    • 2015-05-12
    • 2022-12-27
    • 2012-12-15
    • 2011-03-17
    • 2014-09-27
    • 2012-02-23
    相关资源
    最近更新 更多