简体   繁体   English

如何在Nokogiri中的XML根节点之前添加注释?

[英]How to add a comment before XML root node, in Nokogiri?

This is what I'm doing: 这就是我在做什么:

xml = Nokogiri::XML('<hello/>')
xml.root.add_previous_sibling(
  Nokogiri::XML::Comment.new(
    xml, '<!-- how are you? -->'
  )
)

This is what I'm trying to achieve: 这是我要实现的目标:

<?xml version="1.0"?>
<!-- how are you? -->
<hello/>

I'm getting: 我越来越:

ArgumentError: A document may not have multiple root nodes.

What is the right way? 正确的方法是什么?

Comment should be added inside xml.children NodeSet. 应该在xml.children NodeSet中添加注释。
Here is an example: 这是一个例子:

 xml = Nokogiri::XML('<hello/>')
=> #<Nokogiri::XML::Document:0x3fe1db8d0ed0 name="document" children=[#<Nokogiri::XML::Element:0x3fe1db8d0584 name="hello">]>

xml.children.before(Nokogiri::XML::Comment.new(xml, 'how are you?'))
=> #<Nokogiri::XML::Element:0x3fe1db8d0584 name="hello">

xml.to_s
=> "<?xml version=\"1.0\"?>\n<!--how are you?-->\n<hello/>\n"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM