简体   繁体   中英

Nokogiri HttParty Xpath Ruby on Rails

I am working with a Eve Online request that returns XML. I am using HTTParty for the request, and I am trying to use Nokogiri to obtain attribute values for a specific element.

Here's an example of the response:

 <eveapi version="2"><currentTime>2012-10-19 22:41:56</currentTime><result><rowset  name="transactions" key="refID"  columns="date,refID,refTypeID,ownerName1,ownerID1,ownerName2,ownerID2,argName1,argID1,amount,balance,reason,taxReceiverID,taxAmount"><row date="2012-10-18 23:41:50" refID="232323" refTypeID="9" ownerName1="University of Caille" ownerID1="32232" ownerName2="name" ownerID2="34343" argName1="" argID1="0" amount="5000.00" balance="5000.00" reason="Starter fund" taxReceiverID="" taxAmount=""/></rowset></result><cachedUntil>2012-10-19 23:03:40</cachedUntil></eveapi>

I only need to access attributes for the element "row" and there can be many rows returned.

I read about XPath and, from what I understand, if I do the following it should return all rows: doc.xpath('row') however, it does not return anything.

Here's what I have so far:

options = {:keyID => 111111, :vCode => 'fddfdfdfdf'}
response = HTTParty.post('https://api.eveonline.com/char/WalletJournal.xml.aspx', :body => options)
doc = Nokogiri::XML(response.body)
doc.xpath('row').each do |r|

end

The loop is never executed.

What am I doing wrong? I need to return all row elements and gain access to each of the row's attributes.

Here's the code I had before, which worked until I tried a different character and received a "cannot convert integer to string error":

options = {:keyID => 434343, :vCode => 'fdfdfdfdf'}
response = HTTParty.post('https://api.eveonline.com/char/WalletJournal.xml.aspx', :body => options)
data = response.parsed_response
data['eveapi']['result']['rowset']['row'].each do |t|
  if t['ownerName2'].eql?('name') && !t['reason'].eql?('Starter fund')
    uniqueKey = t['ownerID1'].to_s + t['date']
    if !Payment.exists?(:unique_payment_key => uniqueKey)
      p = Payment.new
      p.owner_id = t['ownerID1']
      p.owner_name = t['ownerName1']
      p.unique_payment_key = uniqueKey
      p.amount = t['amount']
      p.reason = t['reason']
      p.save
    end
  end
end

Sorry, the error is error: can't convert String into Integer online line 42 which is

if t['ownerName2'].eql?('name') && !t['reason'].eql?('Starter fund')

Well, you can fix your immediate problem by using //row instead of row , assuming you want row elements at any depth.

However, HTTParty parses your response for you, so it's a bit redundant use it just to post a page, if you're going to parse it a different way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM