1

Is there a simple way to detect if an XML node exists in Rails?

To get the @result instance variable I use

response, data = Net::HTTP.post_form(url, params)
@result = Hash.from_xml(response.body)

I've tried:

if @result['GetProperties']['Errors'].exists?

or just

if @result['GetProperties']['Errors']

but both result in the following error:

undefined method `[]' for nil:NilClass

I should make clear that I have no problem parsing XML - I just need to know how to detect if a node exists

Simone Carletti
  • 173,507
  • 49
  • 363
  • 364
tommyd456
  • 10,443
  • 26
  • 89
  • 163
  • You must add more details. Either `@result` is nil or `@result['GetProperties']` is. Once you have your XML, drop it into `Nokogiri::XML()`, and use `xpath_at` to get the nodes. – Phlip Jan 06 '14 at 20:11
  • What XML parser/library are you using? What is `@result?` etc. – JKillian Jan 06 '14 at 20:13
  • not using any specific parser at the moment - should I be doing? – tommyd456 Jan 06 '14 at 20:13
  • edited my question to show you what `@result` is – tommyd456 Jan 06 '14 at 20:16
  • Your code still doesn't say if `@result` or `@result['GetProperties']` has the `nil`. And I'd trust Nokogiri more than `Hash.from_xml`, but that's just me. – Phlip Jan 06 '14 at 20:23

1 Answers1

0

Given your additional info - something like this would work:

if @result && @result['GetProperties'] && @result['GetProperties']['Errors']

If Hash.from_xml doesn't ever return nil, (just check the doc on this one, I don't personally know) you could simplify it to:

if @result['GetProperties'] && @result['GetProperties']['Errors']

Finally, if you think that's kind of sloppy, you could consider writing a method of some sort to check for nested properties all at once like here: https://stackoverflow.com/a/1820492/3124288

Community
  • 1
  • 1
JKillian
  • 18,061
  • 8
  • 41
  • 74