簡體   English   中英

如何使用REXML + XPATH從XML文檔中刪除所有注釋?

[英]How to delete all comments from XML document with REXML+XPATH?

我有一個帶有大量注釋的XML文件,這些注釋使該文件變得又大又混亂。 是否可以使用REXML從其中刪除注釋?

我已經嘗試過了,但是它沒有用(盡管,奇怪的是,它也沒有失敗):

doc.elements.each('//comment()') { |n| doc.delete n }

更新

這有效:

require 'rexml/document'

doc = REXML::Document.new "<root><foo><!-- comment --></foo></root>"

doc.elements('//*').each { |n| n.comments().each { |c| c.parent = nil } }

formatter = REXML::Formatters::Pretty.new(4)

formatter.compact = true

puts formatter.write(doc.root, '')

# Output:  
#
# <root>
#    <foo/>
# </root>

我從這里 (ruby-doc.org)獲得了解決方案。

REXML::XPath.match(doc, '//comment()').each(&:remove)

REXML :: XPath是一個類,其中包含用於搜索文檔中節點的方法。 match方法將返回一個節點數組。 第一個參數是一個節點,必須從該節點開始搜索。 第二個參數是用於搜索的xpath。

它返回包含找到的所有元素的數組,然后在其上運行remove方法。 上面的表達式從文檔中刪除所有注釋。

鏈接到REXML :: XPath文檔

嘗試

def del_comments(node)
  node.comments().each { |comment| node.delete comment }
  node.elements().each { |child| del_comments(child) }
end

del_comments(doc)

完整的摘要是

require "rexml/document"
include REXML  # so that we don't have to prefix everything with REXML::...
string = <<EOF
<!-- comment 1 -->
  <mydoc>
    <someelement attribute="nanoo">Text, text, text</someelement>
    <!-- comment 2 -->
    <foo>
      <!-- comment 3 -->
      <bar>whatever</bar>
      <!-- comment 4 -->
    </foo>
    <!-- comment 5 -->
    <baz>...</baz>
    <!-- comment 6 -->
  </mydoc>
<!-- comment 7 -->
EOF

doc = Document.new string

def del_comments(node)
  node.comments().each { |comment| node.delete comment }
  node.elements().each { |child| del_comments(child) }
end

del_comments(doc)

puts doc

哪個輸出

  <mydoc>
    <someelement attribute='nanoo'>Text, text, text</someelement>

    <foo>

      <bar>whatever</bar>

    </foo>

    <baz>...</baz>

  </mydoc>

因此所有評論均被刪除。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM