簡體   English   中英

使用libxml在Ruby中找到元素后刪除該元素

[英]Delete an element after the element is found in Ruby using libxml

我來自C的背景,但是從事與Ruby中的XML相關的工作,所以,如果我的問題很幼稚,請耐心等待。

我有一個XML文檔。 我正在使用libxml解析它:

<test>
 <ready>
  <ex_success>true</ex_success>
 </ready>
 <ath>
  <name>abc</name>
  <pass>123</pass>
  <ex_success>true</ex_success>
 </ath>
</test>

在本文檔中,我能夠閱讀ex_success元素。 但是,我無法將其從原始文件中刪除。

這是我的一小段代碼:

require 'xml'
test_file = @file_name
parser = XML::Parser.file(test_file)
document = parser.parse

document.root.each_element {|element|

  # Write each element name in the file
  puts 'element.name'

  if val = element.find_first('ex_success')   
    puts val.content   # prints true
    val.remove!    # THIS line does not remove the element from my original file

  else
    puts 'Not found'
  end

我在做什么錯,刪除它的正確方法是什么?

我建議不要使用libxml。 盡管它是Ruby的一部分,但它並不是Ruby XML解析的實際標准。 能吉里是。

這是我使用Nokogiri的方法:

require 'nokogiri'

doc = Nokogiri::XML::DocumentFragment.parse(<<EOT)
<test>
 <ready>
  <ex_success>true</ex_success>
 </ready>
 <ath>
  <name>abc</name>
  <pass>123</pass>
  <ex_success>true</ex_success>
 </ath>
</test>
EOT

ex_success = doc.at('ex_success')
ex_success_value = ex_success.text # !> assigned but unused variable - ex_success_value
ex_success.remove

puts doc.to_xml
# >> <test>
# >>  <ready>
# >>   
# >>  </ready>
# >>  <ath>
# >>   <name>abc</name>
# >>   <pass>123</pass>
# >>   <ex_success>true</ex_success>
# >>  </ath>
# >> </test>

如果您不希望空文本節點留下空白行,請使用以下命令:

ex_success = doc.at('ex_success')
ex_success_value = ex_success.text # => "true"
ex_success.parent.children.remove

puts doc.to_xml
# >> <test>
# >>  <ready/>
# >>  <ath>
# >>   <name>abc</name>
# >>   <pass>123</pass>
# >>   <ex_success>true</ex_success>
# >>  </ath>
# >> </test>

我使用了Nokogiri::XML::DocumentFragment.parse ,它按原樣接受XML代碼段。 使用Nokogiri::XML(<<EOT)更為常見,如果不存在,它將添加XML decl。

暫無
暫無

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

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