개발

[XML, JSON] parsing XML and JSON

팥빙구 2015. 1. 8. 14:10

XML

XML (Extensible Markup Language) is very similar to HTML.

It uses tags between angle brackets<>.

The difference is that XML allows you to use tags that you make up, rather than tags that the W3C decided on.

For instance, you could create an API that returns information about a pet:

<pet>

  <name>Jeffrey</name>

  <species>Giraffe</species>

</pet>


We require in the 'rexml/document' module for parsing XML in ruby.

require "rexml/document"


file = File.open("pets.txt")

doc = REXML::Document.new file

file.close


doc.elements.each("pets/pet/name") do |element|

  puts element

end


JSON

JSON (Javascript Object Notation) is an alternative to XML.

It gets its name form the fact that its data format resembles JavaScript objects, and it is often more succinct(간결한) than the equivalent XML. For instance, our same <pet> Jeffrey would look like this in JSON:

{

  "pets": {

    "name": "Jeffrey",

    "species": "Giraffe"

  }

}


We require the 'json' module for parsing JSON in ruby.


XML or JSON?

How do we know whether an API will reply with XML or JSON?

The only way you'll know what type of data an API will send you is to read that API's documentation! Some will reply with one, and some will reply with the other.