How can I serialize a XML node taken from a document into a standalone
document? Using node.to_xml
is not enough, because to_xml
does not
output all the needed namespaces, only those explicitly declared inside
that node.
For example, I have this XML document in doc
<wrapper xmlns="ns" xmlns:extra="extra">
<record xml:id="r1">
<field>aaa</field>
<field extra:type="second">bbb</field>
</record>
</wrapper>
and I want to I isolate the node #r1
.
record = doc.at("//*[@xml:id='r1']")
Now, record.to_xml
returns (reformatted)
<record xml:id="r1">
<field>aaa</field>
<field extra:type="second">bbb</field>
</record>
This result may be OK in some contexts, but it is not good for my
purposes: the default namespace and the extra
namespace have not been
copied. What I want is a document in which all the needed namespaces
have been copied, like the following:
<record xml:id="r1" xmlns="ns" xmlns:extra="extra">
<field>aaa</field>
<field extra:type="second">bbb</field>
</record>
How can I do this with Nokogiri?