我正在尝试使用 Nokogiri 编辑一个大的 XML 文件。目前,我能够找到我正在寻找的 NodeSet,.css
我可以创建我想设置为替换的新 NodeSet,但是通过使用Nokogiri::XML::NodeSet#push
我无法更改 xml 文档对象的内容。
xml = Nokogiri::XML(File.read('/Users/Desktop/metadata.xml')
keywords = xml.css('version').first.css('keywords keyword') ## node set I want to edit
keywords.delete(keywords[0]) ## one less element in the node set
xml.css('version').first.css('keywords keyword').remove ## destructively modifies xml object and erases all elements
## this is where things get interesting:
## this call returns a new node set with keywords[0] inside of it,
## but does NOT mutate the xml object
xml.css('version').first.css('keywords keyword').push(keywords[0])
puts xml.css('version').first.css('keywords keyword') ## puts an empty array
编辑:示例 XML
<version>
<locale name="en-US">
<title>This is the Title</title>
<description>this is the description</description>
<keywords>
<keyword>this</keyword>
<keyword>that</keyword>
<keyword>the other</keyword>
</keywords>
</locale>
</version>
编辑:目标 XML
<version>
<locale name="en-US">
<title>This is the Title</title>
<description>this is the description</description>
<keywords>
<keyword>that</keyword>
<keyword>the other</keyword>
</keywords>
</locale>
</version>
或者
<version>
<locale name="en-US">
<title>This is the Title</title>
<description>this is the description</description>
<keywords>
<keyword>different keyword</keyword>
</keywords>
</locale>
</version>