gpt4 book ai didi

ruby - 如何将 XML 内容包装在新节点(Nokogiri、Ruby)中?

转载 作者:数据小太阳 更新时间:2023-10-29 02:03:45 25 4
gpt4 key购买 nike

使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com