How can I use Ruby for simple XML parsing to query and find specific tag values?

I am working with an API and want to know how I can easily search and display / format tag-based output.

For example, here is an API page and OUtput XML examples:

http://developer.linkedin.com/docs/DOC-1191

I want to be able to process each record as an object, for example, the user name User.first User.last so that I can display and store information and perform a search.

Maybe the stone that makes it easier?

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<people-search>
  <people total="108" count="10" start="0">
    <person>
      <id>tePXJ3SX1o</id>
      <first-name>Bill</first-name>
      <last-name>Doe</last-name>
      <headline>Marketing Professional and Matchmaker</headline>
      <picture-url>http://media.linkedin.com:/....</picture-url>
    </person>
    <person>
      <id>pcfBxmL_Vv</id>
      <first-name>Ed</first-name>
      <last-name>Harris</last-name>
      <headline>Chief Executive Officer</headline>
    </person>
     ...
  </people>
  <num-results>108</num-results>
</people-search>
+3
source share
4 answers

This may give you the start of a transition:

#! / usr / bin / env ruby

require 'nokogiri'

XML = %{<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<people-search>
  <people total="108" count="10" start="0">
    <person>
      <id>tePXJ3SX1o</id>
      <first-name>Bill</first-name>
      <last-name>Doe</last-name>
      <headline>Marketing Professional and Matchmaker</headline>
      <picture-url>http://media.linkedin.com:/foo.png</picture-url>
    </person>
    <person>
      <id>pcfBxmL_Vv</id>
      <first-name>Ed</first-name>
      <last-name>Harris</last-name>
      <headline>Chief Executive Officer</headline>
    </person>
  </people>
  <num-results>108</num-results>
</people-search>}

doc = Nokogiri::XML(XML)

doc.search('//person').each do |person|
    firstname   = person.at('first-name').text
    puts "firstname: #{firstname}"
end
# >> firstname: Bill
# >> firstname: Ed

, , , "", . . Nokogiri.at(), , .

Nokogiri , . .

+4

nokogiri - XML- ruby, xpath css3 xml, xml mapper

xml-mapping, , xpath, , .

+1

Here's how I did it for the Ruby Challenge using the built-in REXML.

This is basically parsing code for the entire document:

doc = REXML::Document.new File.new cia_file
doc.elements.each('cia/continent') { |e| @continents.push Continent.new(e) }
doc.elements.each('cia/country') { |e| @countries.push Country.new(self, e) }
+1
source

http://nokogiri.org/ is an option you should explore

0
source

Source: https://habr.com/ru/post/1762783/


All Articles