首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用Nokogiri解析带有非对标签的XML

如何使用Nokogiri解析带有非对标签的XML
EN

Stack Overflow用户
提问于 2019-03-31 04:08:34
回答 1查看 73关注 0票数 1

在internet上看到的所有示例都是具有如下结构的XML文件:

代码语言:javascript
复制
<open_tag>data that I want</close_tag>

但是我的XML文件是不同的:

代码语言:javascript
复制
<Report xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="_x0034_00_x0020_-_x0020_Nomenklatury" xsi:schemaLocation="_x0034_00_x0020_-_x0020_Nomenklatury http://pcisrs/ReportServer?%2FTARIC%20Reporty%20Ciselnikov%2F400%20-%20Nomenklatury&rs%3AFormat=XML&rc%3ASchema=True" Name="400 - Nomenklatury">
<table1>
<Detail_Collection>
<Detail goods_nomenclature_item_id="0100000000" product_line="80" date_start="31.12.1971" quantity_indents="0" declarable_import="0" declarable_export="0" goods_nomenclature_item_description="ŽIVÉ ZVIERATÁ"/>
<Detail goods_nomenclature_item_id="0101000000" product_line="80" date_start="01.01.1972" quantity_indents="1" statistical_unit="NAR" declarable_import="0" declarable_export="0" goods_nomenclature_item_description="Živé kone, somáre, muly a mulice" parent_goods_nomenclature_item_id="0100000000" parent_product_line="80"/>

.....ETC....

</Detail_Collection>
</table1>
</Report>

如果我理解这些教程,这应该是可行的:

代码语言:javascript
复制
 subor = Nokogiri::XML(File.open('vendor/financnasprava/nomenklatury/recent.xml'))
    dataset = subor.xpath('//Detail')

但并没有。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-04-01 04:46:50

您可以使用以下示例中的数据。我删除了源路径,因为本地没有此数据。

如果我是对的,并且您正在尝试访问详细信息属性:

代码语言:javascript
复制
require 'nokogiri'
require 'open-uri'

data_xml = <<-EOT
<Report xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Name="400 - Nomenklatury">
<table1>
<Detail_Collection>
<Detail goods_nomenclature_item_id="0100000000" product_line="80" date_start="31.12.1971" quantity_indents="0" declarable_import="0" declarable_export="0" goods_nomenclature_item_description="ŽIVÉ ZVIERATÁ"/>
<Detail goods_nomenclature_item_id="0101000000" product_line="80" date_start="01.01.1972" quantity_indents="1" statistical_unit="NAR" declarable_import="0" declarable_export="0" goods_nomenclature_item_description="Živé kone, somáre, muly a mulice" parent_goods_nomenclature_item_id="0100000000" parent_product_line="80"/>
</Detail_Collection>
</table1>
</Report>
EOT
subor = Nokogiri::XML(data_xml)
dataset = subor.xpath('//Detail_Collection/*')
details = dataset.map do |row|
  {
    product_line: row.attributes['product_line'].value,
    goods_nomenclature_item_id: row.attributes['goods_nomenclature_item_id'].value
  }
end

puts details

#=> {:product_line=>"80", :goods_nomenclature_item_id=>"0100000000"}
#=> {:product_line=>"80", :goods_nomenclature_item_id=>"0101000000"}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55435277

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档