Skip to content

Instantly share code, notes, and snippets.

@airspeed
Last active January 24, 2017 16:17
Show Gist options
  • Save airspeed/0444e4ad52d98f51427af67fe751d322 to your computer and use it in GitHub Desktop.
Save airspeed/0444e4ad52d98f51427af67fe751d322 to your computer and use it in GitHub Desktop.
require "nokogiri"
def nokogiri_edit( handle, opts )
builder = Nokogiri::XML::Builder.new( :encoding => 'UTF-8' ) do | xml |
party = false
party_id = false
party_id_system = false
party_id_match = false
party_role = false
party_role_match = false
Nokogiri::XML::Reader( handle ).each do | node |
party = true if node.node_type == 1 && node.name == 'PARTY'
party = false if node.node_type == 15 && node.name == 'PARTY'
# match <bmecat:PARTY_ID>
party_id = true if party && node.node_type == 1 && node.name == 'bmecat:PARTY_ID'
party_id = false if party && node.node_type == 15 && node.name == 'bmecat:PARTY_ID'
party_id_system = true if party_id && node.attribute( 'type' ) == 'systemspecific'
party_id_system = false if !party_id
party_id_val = node.value if party_id_system && node.node_type == 3
party_id_val = nil if !party_id
party_id_match = true if party_id_system && party_id_val == "Address #{ opts[ :address ][ :id ] }"
party_id_match = false if !party
# match <PARTY_ROLE>
party_role = true if party_id_match && node.node_type == 1 && node.name == 'PARTY_ROLE'
party_role = false if party_id_match && node.node_type == 15 && node.name == 'PARTY_ROLE'
party_role_val = node.value if party_role && node.node_type == 3
party_id_val = nil if !party_role
party_role_match = true if party_role && party_role_val == 'delivery'
party_role_match = false if !party
# bmecat:PARTY_ID and PARTY_ROLE have been match, we can be sure that we are editing the correct delivery address.
# match <ADDRESS>
address = true if party_role_match && node.node_type == 1 && node.name == 'ADDRESS'
address = false if party_role_match && node.node_type == 15 && node.name == 'ADDRESS'
# edit ADDRESS
#puts node.outer_xml and address = false if address
doc = Nokogiri::XML( node.outer_xml ) if address
puts doc.xpath( '//bmecat:NAME' ).at( 0 ).content = 'Sven Goran' if doc
end
end
xmlstring = builder.to_xml
end
def start( input, output, opts )
ads = opts[ :addresses ]
ads.each do | a |
xmlstring = nokogiri_edit( File.open( input ), {
:address => a,
:storno => false,
:email => 'ts@clixxie.de'
})
File.open( output, "w" ) do | edit |
edit.puts xmlstring
end
output
end
end
start( '/Users/fpugl/Downloads/PX36103.xml', '/Users/fpugl/Downloads/PX36103.xml.edit', {
:addresses => [ { :id => 'PX44255', :name => 'Martin', :surname => 'Mystere', :company => 'Femory', :street => 'Fraunhoferstraße 6' } ],
:storno => false,
:email => 'ts@clixxie.de'
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment