Reputation: 15
I'm trying to build off of a previously asked question (How do I merge two XML files into one using Nokogiri?), but I'm having some difficulty.
I would like to import the content of "mat" from the first XML file into the second XML file only if the element ids match. This is what I have so far...
require 'nokogiri'
xml1 = Nokogiri::XML('<?xml version="1.0"?>
<formX xmlns="sdu:x">
<identify>
<mat id="a">8</mat>
</identify>
<identify>
<mat id="b">7</mat>
</identify>
</formX>')
xml2 = Nokogiri::XML('<?xml version="1.0"?>
<formX xmlns="sdu:x">
<identify>
<mat id="a">9999</mat>
<name>John Smith</name>
</identify>
<identify>
<mat id="b">9999</mat>
<name>Jane Smith</name>
</identify>
</formX>')
xml2.css('mat').each do |node|
if xml2.at('mat')['id'] == xml1.at('mat')['id']
node.content = xml1.at('mat').content
end
end
puts xml2.to_xml
And, I receive the following output...
<?xml version="1.0"?>
<formX xmlns="sdu:x">
<identify>
<mat id="a">8</mat>
<name>John Smith</name>
</identify>
<identify>
<mat id="b">8</mat>
<name>Jane Smith</name>
</identify>
</formX>
But, I'm shooting for...
<?xml version="1.0"?>
<formX xmlns="sdu:x">
<identify>
<mat id="a">8</mat>
<name>John Smith</name>
</identify>
<identify>
<mat id="b">7</mat>
<name>Jane Smith</name>
</identify>
</formX>
Any help would be appreciated. Thanks!
Upvotes: 1
Views: 973
Reputation: 441
The way you find the same id element is not right. This works:
xml2.css('mat').each do |node2|
xml1.css('mat').each do |node1|
if node1['id'] == node2['id']
node2.content = node1.content
end
end
end
puts xml2.to_xml
Upvotes: 1