如何使用Nokogiri从哈希构建节点



很多人通常想做相反的变换,但我想从Ruby哈希(有许多嵌套哈希甚至数组)构建一个节点:

my_hash = {
  "name" => "Something",
  "property_1" => "Something"
  "nested_array_items" => [{ "name" => "Nasty nested array item", 
                  "advice" => "Use recursive function" },
                 { "name" => "yes this is an array",
                  "notice" => "not necessarily the same keys"}],
  "nested_many_levels" => { "additional_items" => { "ok_stop_here" => true } },
}

我有一个应该包含所有这些的Nokogiri节点。如何定义函数来执行此操作?

每个子节点应该用键的名称命名,最终将"_"替换为"-"。对于数组,对每个项目使用键名称的单数,假设它是常规复数(以"s"结尾,否则引发错误)。

例如,上面给出的哈希值应变为:

...
<name>something></name>
<property_1>Something</property_1>
<nested_array_items>
  <nested_array_item>
    <name>Nasty nested array item</name>
    <advice>Use recursive function</advice>
  </nested_array_item>
  <nested_array_item>
    <name>yes this is an array</name>
    <notice>not necessarily the same keys</notice>
  </nested_array_item>
</nested_array_items>
<nested_many_levels>
  <additional_items>
      <ok_stop_here>true</ok_stop_here>
  </additional_items>
</nested_many_levels>
...

好的,所以我意识到从哈希构建节点不是我的最佳选择(就我而言,我希望拥有完整的 XML 结构,即使某些节点由于缺少哈希内容而为空)。

因此,我正在使用一个 XML 模板节点,该节点已经包含我想要的完整结构,只有长度为 1 的数组。因此,与其构建新节点,不如根据需要多次复制现有节点(预处理),然后替换内容。

因为这只对数组来说是痛苦的,让我们假设我的contents变量,对于第一次调用,只是一个包含数组的哈希(但这些数组的项目可以是值,哈希,...)

复制custom_xml的模板节点

contents.map do |content, items|
    tmp = custom_xml.search("#{content.to_s}")      # Should be unique !
    if tmp.count > 1 then raise "ERROR : multiple nodes match XPATH //#{content.to_s}" end
    if tmp.count == 0 then raise "ERROR : No node matches "search #{content.to_s}" DEBUG : #{custom_xml.serialize}" end
    array_node = tmp.first # <array><item>...</item></array>
    template_node = array_node.first_element_child  
    # Okay, we have the customXML node corresponding to the first item of the content
    # We need to duplicate it as many times as needed
    items.each_with_index do |item, item_index|
        next if item_index == 0 # Skip the first one.
        array_node << template_node.dup
    end
end

然后,在完成此预处理之后,可以通过调用replace_node_vars_recursively(array_node, items)来实际替换array_node的变量

请注意,对于第一次调用,我们确实有一个array_node items,但递归函数也需要处理哈希和值。因此,让我们用content这个词来指定这些东西,然后node

使用"内容"递归更改节点文本

def  replace_node_vars_recursively(node, content)
    if content.nil?
        puts "WARNING : nil content trying to be assigned to node #{node.name}"
    elsif content.is_a?(Hash)
        # Every key in content SHOULD have a matching child node !
        content.each do |key, val|
            candidates = node.search("#{key.to_s}")     # Should be unique !
            if candidates.count > 1 
                puts "WARNING : multiple child_nodes match -->#{key.to_s}<--, skipping"
                next
            elsif candidates.count == 0 
                puts "WARNING : No child node matches "#{key.to_s}" "
                next
            end
            replace_node_vars_recursively(candidates.first, val)
        end
    # Array recursion (rq : array contains either a Hash or a value.)
    elsif content.is_a?(Array)
        # Let's rename the variables !
        array_items = content 
        array_node = node
        if array_items.count != array_node.element_children.count # /! using just "children" will return empty nodes !!!
            raise "ERROR : array length (#{array_items.count}) != number of nodes of #{array_node.name} (#{array_node.element_children.count}) !"
        end
        array_node.element_children.each_with_index do |child_node, index|  # Assume item is another content_hash. Wouldn't make sense (for me) to have just a value there...
            replace_node_vars_recursively(child_node, content[index])
        end
    # Value terminaison
    elsif content.is_a?(String) or content.is_a?(Integer) or content.is_a?(Float) or content.is_a?(Symbol) or content.is_a?(Date) or content.is_a?(Datetime)
        node.content = content.to_s
        puts "Replacing variable #{node.name} by #{content.to_s}"
    else 
        puts content
        raise "ERROR: unknown variable type for variable replacement !"
    end
end

好的,这是我的代码似乎有效!

def  build_node_recursively(node, content_hash, xml_document)
    content_hash.each do |key, val|
        new_node = Nokogiri::XML::Node.new "#{key.to_s}", xml_document
        # Val can be : a value | an array of hashes | another hash
        if val.is_a?(Array)
            item_label = key.to_s.singularize
            val.each do |item|  # Assume item is another content_hash. Wouldn't make sense (for me) to have just a value...
                item_node = Nokogiri::XML::Node.new item_label, xml_document
                new_node << build_node_recursively(item_node, item)
            end
        elsif val.is_a?(Hash)
            build_node_recursively(new_node, val)
        else
            new_node.content = val.to_s
        end
        node << new_node
    end
end

相关内容

  • 没有找到相关文章

最新更新