Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove comment nodes?

Tags:

xml

ruby

nokogiri

I have an XML document with many comment tags I want to uncomment. For example:

<bean id="metadata" class="org.archive.modules.CrawlMetadata" autowire="byName">
   <!-- <property name="robotsPolicyName" value="obey"/> -->
   <!-- <property name="operator" value=""/> -->
   <!-- <property name="operatorFrom" value=""/> -->
   <!-- <property name="organization" value=""/> -->
   <!-- <property name="audience" value=""/> -->
</bean>

I'm using Nokogiri. Is there any way to remove the comments on the nodes, or to locate them, even when as comments, delete and re-create?

like image 649
Jonathan García Avatar asked Jun 02 '26 07:06

Jonathan García


1 Answers

It looks like you want to replace the comments with their content, so uncommenting the markup?

That is easily done:

require 'nokogiri'

doc = Nokogiri::XML::Document.parse(<<__XML__)
<bean id="metadata" class="org.archive.modules.CrawlMetadata" autowire="byName">
<!-- <property name="robotsPolicyName" value="obey"/> -->
<!-- <property name="operator" value=""/> -->
<!-- <property name="operatorFrom" value=""/> -->
<!-- <property name="organization" value=""/> -->
<!-- <property name="audience" value=""/> -->
</bean>
__XML__

doc.xpath('//comment()').each { |comment| comment.replace(comment.text) }

puts doc.serialize

output

<?xml version="1.0"?>
<bean id="metadata" class="org.archive.modules.CrawlMetadata" autowire="byName">
 <property name="robotsPolicyName" value="obey"/> 
 <property name="operator" value=""/> 
 <property name="operatorFrom" value=""/> 
 <property name="organization" value=""/> 
 <property name="audience" value=""/> 
</bean>
like image 58
Borodin Avatar answered Jun 04 '26 02:06

Borodin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!