简体   繁体   English

注释掉Nokogiri XML中的节点?

[英]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: 执行以下操作以基于xpath注释出给定的一个或多个节点:

  1. Use the .xpath method to find the target nodes. 使用.xpath方法查找目标节点。
  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. 此代码将基于num="2"属性注释掉第二个<child>

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: 完成该过程后, doc.to_xml将为:

<?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. Nokogiri产生的注释在<!---->标记之间以及添加的任何内容之间没有空格。 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. 尽管可能有解决的办法,但如果您担心美学问题,请准备好花些时间将其弄乱。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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