1

鉴于我现有的 XML (test.xml):

<root>
  <element>
    <child id="1" />
    <child id="2" />
    <child id="3" />
  </element>
</root>

还有我的红宝石代码:

require 'rubygems'
require 'xml'

parser = XML::Parser.file("test.xml")
doc = parser.parse

target = doc.find('/*/element')
target << child = XML::Node.new('child')
child['id'] = '4'

XML.indent_tree_output = true
doc.save(filename, :indent => true, :encoding => XML::Encoding::UTF_8)

我的问题是它像这样格式化输出:

<root>
  <element>
    <child id="1" />
    <child id="2" />
    <child id="3" />
  <child id="4" /></element>
</root>

...随后添加如下所示:

<root>
  <element>
    <child id="1" />
    <child id="2" />
    <child id="3" />
  <child id="4" /><child id="5" /><child id="6" /></element>
</root>

想要的是:

<root>
  <element>
    <child id="1" />
    <child id="2" />
    <child id="3" />
    <child id="4" />
    <child id="5" />
    <child id="6" />
  </element>
</root>

...但我怎么得到它?

4

2 回答 2

2

代替
parser = XML::Parser.file("test.xml")


parser = XML::Parser.file("test.xml", :options => XML::Parser::Options::NOBLANKS )

这是帮助

于 2009-05-12T10:49:06.803 回答
0

如果您使用的是 document.save,请确保将 indent 设置为 true,同时确保设置了 XML.indent_tree_output。像这样的东西:

XML.indent_tree_output = true
doc.save(filename, :indent => true, :encoding => XML::Encoding::UTF_8)

Rubyforge 不适合我,所以我无法在文档中验证它,但我认为两者都需要设置为 true 才能缩进和换行。

于 2009-04-02T19:01:23.367 回答