我有一个需要大量XML数据并将其传递给Nokogiri的项目,最终将每个元素添加到散列输出到YAML文件。如何将XML中的重复键添加到散列
这是有效的,直到XML数据集包含重复键。
实施例的数据:
<document>
<form xmlns="">
<title>
<main-title>Foo</main-title>
</title>
<homes>
<home>
<home-name>home 1</home-name>
<home-price>10</home-price>
</home>
<home>
<home-name>home 2</home-name>
<home-price>20</home-price>
</home>
</homes>
</form>
</document>
内homes
元件I可以具有多个住宅,但每种home
将总是包含不同的内容。
这个数据应该最终输出这样的结构:
title:
main-title: Foo
homes:
home:
home-name: home 1
home-price: 10
home:
home-name: home 2
home-price: 20
但是,所有我曾经得到的是内部homes
title:
main-title: Foo
homes:
home:
home-name: home 2
home-price: 20
我相信这是最后一个元素,因为添加的每个元素时如果它已经存在,它将简单地覆盖该密钥,因此总是给我最后一个密钥。
这是用于追加元素的哈希代码:
def map_content(nodes, content_hash)
nodes.map do |element|
case element
when Nokogiri::XML::Element
child_content = map_content(element.children, {})
content_hash[element.name] = child_content unless child_content.empty?
when Nokogiri::XML::Text
return element.content
end
end
content_hash
end
我相信
content_hash[element.name] = child_content
是罪魁祸首,但是这个代码创建具有这些类型的重复键的类似YAML文件,我想保留这个功能,所以我不想简单地为数据散列添加一个唯一的键,因为这意味着我需要修改许多方法并更新它们如何从YAML文件中提取数据。
我读了约compare_by_identity
但不知道如何实现这一点。
我尝试使用compare_by_identity
但它只是导致空YAML文件,所以也许它生成哈希,但它不能被写入YAML文件中?
def map_content(nodes, content_hash)
content_hash = content_hash.compare_by_identity
nodes.map do |element|
case element
when Nokogiri::XML::Element
child_content = map_content(element.children, {})
content_hash[element.name] = child_content unless child_content.empty?
when Nokogiri::XML::Text
return element.content
end
end
content_hash
end
end
怎么样在阵列,具有其下一个 '家' 键,把一切?你所建议的结构将不起作用,因为它将在将其加载回应用程序时给出相同的结果(只有最后一个:主键)。 – Severin
嗯我试图不修改当前结构,但这可能是唯一的方法。 – chinds
您所需的YAML输出是不可能的。 YAML在分析时会产生一个带重复键的散列,你已经发现这是不可能的。你必须使用哈希数组。 –