我希望使用nokogiri将包含任意用户提供的数据的xml文档包含在另一个中。
我尝试了Node#add_child
并遇到了一个问题:如果child_doc
中的uri也出现在主doc
中但前缀不同,则nokogiri会丢失命名空间定义。
示例:
doc = Nokogiri::XML %(
<s:rack xmlns:s="urn://shelf">
<s:shelf></s:shelf>
</s:rack>
)
child_doc = Nokogiri::XML %(
<m:shelf xmlns:m="urn://shelf">
<m:book></m:book>
</m:shelf>
)
doc.root.add_child(child_doc.root)
doc.to_xml
# =>
# <s:rack xmlns:s="urn://shelf">
# <s:shelf/>
# <!-- namespace for prefix m is not declared! -->
# <m:shelf>
# <m:book/>
# </m:shelf>
# </s:rack>
前缀m
的命名空间丢失。
这是生成的doc对象,非常印刷:
#(Document:0x1b2ce28 {
name = "document",
children = [
#(Element:0x1b327c4 {
name = "rack",
namespace = #(Namespace:0x1b320a8 { prefix = "s", href = "urn://shelf" }),
children = [
#(Text "\n "),
#(Element:0x1b45f90 { name = "shelf", namespace = #(Namespace:0x1b320a8 { prefix = "s", href = "urn://shelf" }) }),
#(Text "\n "),
#(Element:0x1a9e5d8 {
name = "shelf",
namespace = #(Namespace:0x1a87450 { prefix = "m", href = "urn://shelf" }),
children = [
#(Text "\n "),
#(Element:0x1a41dec { name = "book", namespace = #(Namespace:0x1a87450 { prefix = "m", href = "urn://shelf" }) }),
#(Text "\n ")]
})]
})]
})
正如您所看到的,添加节点中的内部命名空间是正确的,但序列化错误。如何让nokogiri将它们保存在生成的xml中?