我正在使用 API,想知道如何根据标签轻松搜索和显示/格式化输出。
例如,这是包含 API 和 XML 输出示例的页面:
http://developer.linkedin.com/docs/DOC-1191
我希望能够将每条记录视为一个对象,例如 User.first-name User.last-name 以便我可以显示和存储信息以及进行搜索。
可能有什么 gem 可以让这件事更容易做到吗?
<?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>
最佳答案
这可能会给你一个快速的开始:
#!/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 站点有很好的例子和写得很好的文档,所以一定要花点时间浏览一下。您应该会发现它很容易上手。
关于ruby - 如何使用 Ruby 轻松解析 XML 以查询和查找某些标记值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3623920/