Skip to content

Commit

Permalink
add order to json, since json does not guarantee the order of inserte…
Browse files Browse the repository at this point in the history
…d keys, but it is important for xml
  • Loading branch information
kkoehn committed Oct 18, 2023
1 parent 61934f6 commit 2585691
Show file tree
Hide file tree
Showing 3 changed files with 161 additions and 62 deletions.
6 changes: 3 additions & 3 deletions lib/dachsfisch/json2_xml_converter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ def execute
def add_element(xml, element)
return unless element.is_a? Hash

element.each do |key, value|
add_node(xml, key, value) unless key.start_with?('@')
element['@@order']&.each do |key|
add_node(xml, key, element[key]) unless key.start_with?('@')
end
end

Expand All @@ -44,7 +44,7 @@ def add_node(xml, key, element)
end

def handle_attribute_and_namespaces(node, element)
element.keys.filter {|element_key| element_key.start_with?('@') }.each do |attribute_key|
element.keys.filter {|element_key| element_key.start_with?(/@[^@]/) }.each do |attribute_key|
if attribute_key.start_with? '@xmlns'
element[attribute_key].each do |namespace_key, namespace|
# add namespace of current scope to node. The root-ns($) gets 'xmlns' as key, named namespaces 'xmlns:name' respectively.
Expand Down
9 changes: 8 additions & 1 deletion lib/dachsfisch/xml2_json_converter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,20 +14,27 @@ def execute
@fragment.elements.deconstruct.each do |root|
result[node_name(root)] = extract_node(root)
end
add_order_to_hash result
result.to_json
end

private

def add_order_to_hash(hash)
return if hash.keys.reject {|key| key.start_with?('@') }.empty?

hash['@@order'] = hash.keys.reject {|key| key.start_with?('@') }
end

def extract_node(node)
hash = {}
active_namespaces = add_namespaces_to_active_namespaces(node)
hash['@xmlns'] = active_namespaces unless active_namespaces.empty?

handle_attributes(hash, node)
node.children.each do |child|
handle_content(hash, child)
end
add_order_to_hash hash
hash
end

Expand Down
Loading

0 comments on commit 2585691

Please sign in to comment.