0

My xml:

http://www.google.ru/ig/api?weather=Chelyabinsk

<forecast_information>
  <city data="Chelyabinsk, Province of Chelyabinsk"/>
</forecast_information>

How to get city data for example? Not inner_html, just attributes like city data, postal code etc.

2 Answers2

1

XPath will be a big help when parsing XML. Looks like hpricot has support for it, so it's incredibly easy.

The XPath expression to extract the data attribute inside a city element is as follows:

/forecast_information/city/@data

The expression says, find the attribute named data (that's what the @ sign means) inside the element named city, which is in turn inside the element named forecast_information.

Now, the XML you linked on google.ru is more complicated than the example you posted here. To extract the same information from it, use this expression:

//city/@data

This expression says, find the attribute named data inside the element named city, no matter where city is in the source XML.

Welbog
  • 59,154
  • 9
  • 110
  • 123
1

The selected answer didn't work for me, but the xpath part put me on the right track. This is what I ended up with:

doc = Hpricot::XML(xml)
result = doc.at("//city")['data']

Here is my full parser in ruby for an xml element like this:

  <Response Field1="abc" Field2="123">

  def parse(xml)
    vars = {}
    fields = %w[Field1 Field2 Field3]
    doc = Hpricot::XML(xml)
    for field in fields
      vars[field] = doc.at("//Response")[field]
    end
    return vars
  end
cbron
  • 4,036
  • 3
  • 33
  • 40