简体   繁体   中英

Comment out a node in Nokogiri XML?

Currently I'm removing curtain nodes form a document using:

doc.search('//xpathExpression').each do |node|
    node.remove
end

However, I really need to comment out the nodes rather than delete them. Is there a simple way to change the node type/comment out the current node?

To give credit where it's due, this is the method suggested by the original user in the comments above.


Do the following to comment out a given node or nodes based on an xpath:

  1. Use the .xpath method to find the target nodes.
  2. Prepend each node that's retuned with a copy of the node that's converted to a string inside a comment object.
  3. Remove the original node.

For example, given:

#!/usr/bin/env ruby 

require "nokogiri"

xml = %{
<top>
  <child num="1"/>
  <child num="2"/>
</top>
}

doc = Nokogiri::XML(xml)

This code will comment out the second <child> based on the num="2" attribute.

doc.xpath("//top/child[@num='2']").each do |node|
  node.add_previous_sibling( Nokogiri::XML::Comment.new(doc, " #{node.to_s} ") ) 
  node.remove
end

After that process, doc.to_xml will be:

<?xml version="1.0"?>
<top>
  <child num="1"/>
  <!-- <child num="2"/> -->
</top>

Additional info:

  • The comments produced by Nokogiri don't have white space between the <!-- and --> tokens and whatever content is added. The example above adds leading and trailing space. If that's not a concern, the node can be output with

     Nokogiri::XML::Comment.new(doc, node.to_s) 
  • There doesn't seem to be a straightforward to do automatic pretty printing inside a comment. While there's likely a way around it, be ready to spend some time messing with it if you're concerned with the aesthetics.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM