views:

187

answers:

1

Hey guys,

I'm using Nokogiri to parse a return from the Rackspace API so I'm using their sample code to

   response = server.get '/customers/'[email protected]_id.to_s+'/domains/', server.xml_format
   doc = Nokogiri::XML::parse response.body
   puts "xpath values"
   doc.xpath("//name").each do |node|
   puts
     node.text
   end

As my code to use Nokogiri to return the nodelist of nodes of the element

for some reason I seem to have missed something obvious and I just for the life of me cannot get it to parse the list of nodes and return them to me, is there something simple I can do to fix to have it return the list of nodes?

Here's an example of the XML I'm trying to parse:

   <domainList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="urn:xml:domainList">
  <offset>0</offset>
  <size>50</size>
  <total>4</total>
  <domains>
    <domain>
      <name>domain1.com</name>
      <accountNumber>xxxxxxx</accountNumber>
      <serviceType>exchange</serviceType>
    </domain>
    <domain>
      <name>domain2.com</name>
      <accountNumber>xxxxxxx</accountNumber>
      <serviceType>exchange</serviceType>
    </domain>
    <domain>
      <name>domain3.com</name>
      <accountNumber>xxxxxxx</accountNumber>
      <serviceType>exchange</serviceType>
    </domain>
  </domains>
</domainList>

Cheers

+1  A: 

The issue seems to be that you have to tell Nokogiri about their namespace.

If you remove xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="urn:xml:domainList" from your domainLists tag you'd see your query work.

Otherwise you need to tell Nokogiri about that namespace.

doc.xpath("//blarg:name", {'blarg' => 'urn:xml:domainList'}).each do |name|
  puts name.text
end

Nokogiri xpath takes a second argument which is a hash of namespaces. The xml you have defines a general namespace but doesn't give it a tag. I don't know if there is a way for nokogiri to just find this, so instead on your searches just give your search an arbitrary tag and associate the namespace path with that tag. You can put whatever text you want instead of blarg, it was just for the example.

Beanish
You are an absolute lifesaver, THANK YOU!
Schroedinger