作者热门文章
- xml - AJAX/Jquery XML 解析
- 具有多重继承的 XML 模式
- .net - 枚举序列化 Json 与 XML
- XML 简单类型、简单内容、复杂类型、复杂内容
使用 Nokogiri 我想插入一个节点 <inserted_node>
进入以下 XML 片段
<foo>
<bar>some text</bar>
</foo>
那样
<foo>
<inserted_node>
<bar>some text</bar>
</inserted_node>
</foo>.
Nokogiri 如何实现这一目标?
最佳答案
Nokogiri 有一个名为 wrap
的方法。
doc.search("bar").wrap("<inserted_node>")
doc.to_html
=> <foo>
<inserted_node><bar>some text</bar></inserted_node>
</foo>
回答后续问题:
str = "<foo><bar1></bar1><bar2></bar2></foo>"
doc = Nokogiri::XML(str)
doc.search("bar1,bar2").map(&:parent).uniq.each do |node|
# Create a new element to attach the children to
inserted = doc.create_element("inserted")
# Move the children into the new element
inserted.children = node.children
# Add the new element as a child of the parent node
node << inserted
end
=> "<foo><inserted><bar1></bar1><bar2></bar2></inserted></foo>"
关于ruby - 如何将 XML 内容包装在新节点(Nokogiri、Ruby)中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26476091/
我是一名优秀的程序员,十分优秀!