Reputation: 154
I have a piece of ruby code to replace the value of an attribute:
# -*- coding: utf-8 -*-
require "nokogiri"
xml = <<-eos
<a blubb="blah">
<b>irrelevant</b>
<b>also irrelevant</b>
<b blubb="blah">
<c>irrelevant</c>
<c>irrelevant</c>
</b>
<b blubb="foo">
<c>irrelevant</c>
<c>irrelevant</c>
</b>
</a>
eos
doc = Nokogiri::XML(xml) { |config| config.noent }
doc.xpath("//*[@blubb='blah']").each {|node|
puts "Node before:\n#{node.to_s}" ## replace me!
node['blubb'] = "NEW"
puts "Node after:\n#{node.to_s}" ## replace me!
}
When i execute this code, i get the whole node
element printed, but I only need to see the start tag to confirm that my script works correctly. Is there a way to display only the start tags of node
, or at least only the element itself without its child nodes? The important thing is that the node itself doesn't change when printed (beside the replacement in the attribute), so removing the children is not an option!
Upvotes: 0
Views: 97
Reputation: 8479
We can print name
and attribute_nodes
of the node
doc.xpath("//*[@blubb='blah']").each {|node|
puts "Node before:\n #{node.name} "+node.attribute_nodes.reduce('') { |out, n| out+="#{n.name}=#{n.value}'"}
node['blubb'] = "NEW"
puts "Node after:\n #{node.name} "+node.attribute_nodes.reduce('') { |out, n| out+="#{n.name}='#{n.value}'"}
}
Upvotes: 1