使用Nokogiri将XML提要解析为Ruby对象?

时间:2021-07-24 01:16:59

I am pretty green with coding in Ruby but am trying to pull an XML feed into a Ruby object:

我对用Ruby编写代码非常熟悉,但我正试图将XML提要拉到Ruby对象中:

<% doc = Nokogiri::XML(open("http://api.workflowmax.com/job.api/current?apiKey=#{@feed.service.api_key}&accountKey=#{@feed.service.account_key}")) %>

<% doc.xpath('//Jobs/Job').each do |node| %>
    <h2><%= node['name'].text %></h2>
    <p><%= node['description'].text %></p>
<% end %>

Basically, I want to iterate through each Job and output the name, description etc.

基本上,我想遍历每个作业并输出名称、描述等。

What am I missing?

我缺少什么?

1 个解决方案

#1


5  

Well, since you haven't shown us any sample XML, I'm going to go out on a limb and say that it is not likely the description is in an attribute. You've used the syntax to extract 'name' and 'description' attributes from the 'job' element. If instead they are nested elements you want something like this:

既然你没有给我们展示任何XML样本,我就会说它不太可能是一个属性。您已经使用了语法从“job”元素中提取“name”和“description”属性。如果它们是嵌套元素,则需要如下内容:

<% doc.xpath('//Jobs/Job').each do |node| %>
    <h2><%= node.xpath('name').inner_text %></h2>
    <p><%= node.xpath('description').inner_text %></p>
<% end %>

#1


5  

Well, since you haven't shown us any sample XML, I'm going to go out on a limb and say that it is not likely the description is in an attribute. You've used the syntax to extract 'name' and 'description' attributes from the 'job' element. If instead they are nested elements you want something like this:

既然你没有给我们展示任何XML样本,我就会说它不太可能是一个属性。您已经使用了语法从“job”元素中提取“name”和“description”属性。如果它们是嵌套元素,则需要如下内容:

<% doc.xpath('//Jobs/Job').each do |node| %>
    <h2><%= node.xpath('name').inner_text %></h2>
    <p><%= node.xpath('description').inner_text %></p>
<% end %>