你的兩個例子是迷茫的:它們都表現出完全相同的行爲,但你說其中一個做了一些不同的事情。
據我所知,指定noblanks
從來沒有擺脫空節點:
xml.xml:
<?xml version="1.0"?>
<root>
<installation id="ayfw-a"></installation>
<dog></dog>
<cat/>
</root>
。
require 'nokogiri'
data = Nokogiri::XML(IO.read('xml.xml')) { |doc| doc.noblanks }
puts data
--output:--
<?xml version="1.0"?>
<root>
<installation id="ayfw-a"/>
<dog/>
<cat/>
</root>
我希望可以將輸出爲:
<root>
<installation id="ayfw-a"></installation>
</root>
當然,可怕的引入nokogiri文檔(典型的Ruby)不定義一個空白點是什麼。顯然,什麼noblanks
做的程度是轉換節點是這樣的:
<dog></dog>
到:
<dog/>
更新
啊,所以你的問題是你的XML漂亮的打印。好的,我看到了你所做的同樣的問題。讓我告訴你,你怎麼會問你的問題:
我無法格式化我的XML我想要的方式:
xml.xml:
<?xml version="1.0"?>
<installation id="ayfw-a">
</installation>
。
require 'nokogiri'
data = Nokogiri::XML(IO.read('xml.xml')) {|doc| doc.noblanks}
new_record = Nokogiri::XML::Node.new('tag', data)
data.root.add_child(new_record)
puts data.to_xml(indent: 4, indent_text: ".")
--output:--
<?xml version="1.0"?>
<installation id="ayfw-a">
<tag/></installation>
to_xml()
方法似乎不能正常工作。我預計輸出爲:
<?xml version="1.0"?>
<installation id="ayfw-a">
....<tag/>
</installation>
但to_xml()
方法不格式化輸出我要當標籤具有預先存在的子節點的方式:
xml.xml:
<?xml version="1.0"?>
<installation id="ayfw-a">
<dog>Rover</dog>
</installation>
。
require 'nokogiri'
data = Nokogiri::XML(IO.read('xml.xml')) {|doc| doc.noblanks}
new_record = Nokogiri::XML::Node.new('tag', data)
data.root.add_child(new_record)
puts data.to_xml(indent: 4, indent_text: ".")
--output:--
<?xml version="1.0"?>
<installation id="ayfw-a">
....<dog>Rover</dog>
....<tag/>
</installation>
我如何引入nokogiri格式化輸出我想在第一種情況下的方式嗎?
它看起來不像Nokogiri有一個非常漂亮的打印機。看來,REXML有一個更好的漂亮打印機比引入nokogiri:
xml.xml:
<?xml version="1.0"?>
<installation id="ayfw-a">
</installation>
。
require 'nokogiri'
data = Nokogiri::XML(IO.read('xml.xml')) {|doc| doc.noblanks}
new_record = Nokogiri::XML::Node.new('tag', data)
data.root.add_child(new_record)
puts data.to_xml(indent: 4, indent_text: ".")
require "rexml/document"
REXML::Document.new(data.to_xml).write(File.open("output.txt", "w"), indent_spaces = 4)
--output:--
<installation id="ayfw-a">
<tag/></installation>
$ cat output.txt
<?xml version='1.0'?>
<installation id='ayfw-a'>
<tag/>
</installation>
我喜歡你的努力.. :)) –
@Babai,謝謝! – 7stud