Xoko nokogiri output namespaces

I am trying to isolate a part of an XML document that uses namespaces using nokogiri:

require 'nokogiri'
xml= "<s:Some xmlns:s=\"http://nmsc.com/nmsc\"><s:One></s:One></s:Some>"
n= Nokogiri.XML(xml)
n.xpath("//s:One", :s=>"http://nmsc.com/nmsc")[0].to_xml

This ignores the namespace and simply outputs

"<s:One/>"

How can I generate XML with the correct namespace, i.e.:

<s:One xmlns:s="http://nmsc.com/nmsc" />

?

Interestingly, there is a namespace:

> n.xpath("//s:One", :s=>"http://nmsc.com/nmsc")[0]
=> #(Element:0x3fb1a05d0ed0 {
  name = "One",
  namespace = #(Namespace:0x3fb1a05d1fc4 {
    prefix = "s",
    href = "http://nmsc.com/nmsc"
    })
  })

but to_xmldoes not include it.

+3
source share
1 answer

If you create a new XML document and add the selected node to it, namespace information will be added:

require 'nokogiri'
xml = "<s:Some xmlns:s=\"http://nmsc.com/nmsc\"><s:One></s:One></s:Some>"
n = Nokogiri.XML(xml)
selected = n.xpath("//s:One", :s=>"http://nmsc.com/nmsc")[0]

doc = Nokogiri::XML::Document.new
doc.root = selected
puts doc.to_xml

output:

<?xml version="1.0"?>
<s:One xmlns:s="http://nmsc.com/nmsc"/>
+4
source

All Articles