Ruby:libxml-ruby 并添加格式良好的同级节点
给定我现有的 XML (test.xml):
<root>
<element>
<child id="1" />
<child id="2" />
<child id="3" />
</element>
</root>
和我的 ruby 代码:
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>
。 ..但是我怎样才能得到它呢?
Given my existing XML (test.xml):
<root>
<element>
<child id="1" />
<child id="2" />
<child id="3" />
</element>
</root>
And my ruby code:
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)
My problem is that it formats the output like this:
<root>
<element>
<child id="1" />
<child id="2" />
<child id="3" />
<child id="4" /></element>
</root>
... with subsequent additions looking like this:
<root>
<element>
<child id="1" />
<child id="2" />
<child id="3" />
<child id="4" /><child id="5" /><child id="6" /></element>
</root>
What I WANT is this:
<root>
<element>
<child id="1" />
<child id="2" />
<child id="3" />
<child id="4" />
<child id="5" />
<child id="6" />
</element>
</root>
... but how do I get it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
替换
parser = XML::Parser.file("test.xml")
与
parser = XML::Parser.file("test.xml", :options => XML::Parser::Options::NOBLANKS )
这是帮助
replace
parser = XML::Parser.file("test.xml")
with
parser = XML::Parser.file("test.xml", :options => XML::Parser::Options::NOBLANKS )
that's help
如果您使用的是 document.save,请确保将 indent 设置为 true,并确保设置了 XML.indent_tree_output。 像这样的事情:
Rubyforge 不适合我,所以我无法在文档中验证它,但我认为两者都需要设置为 true 才能缩进和新行工作。
If you're using document.save then make sure you set indent to true, also make sure XML.indent_tree_output is set. Something like this:
Rubyforge isn't working for me so I can't verify it in the documentation, but I think both need to be set to true for indenting and new lines to work.