简体   繁体   中英

Ruby libXML Xpath find returns result in result

Parsing a XML document with Ruby libXML i noticed a strange behaviour. When searching for some elements and traversing the result, I get the result object back in the result itself.

Here's an example XML

<?xml version="1.0" encoding="UTF-8"?>
<main>
    <projects>
        <project id="1">
            <name>Project 1</name>
            <van>Guus</van>
        </project>
        <project id="2">
            <name>Project 2</name>
            <van>Guus</van>
        </project>
    </projects>
</main>

Parsing the code (controller):

 @projects = @xmlDoc.find('//project[@id]/name')

Displaying it (view):

<ul>
<%= @projects.each do |pr| %>
    <li><%= pr.first.content %></li>
<% end %>
</ul>
<hr>
<%= @projects.inspect%>

Results in:

- Project 1
- Project 2
  #<LibXML::XML::XPath::Object:0x000008153182c0>  
------------------------------------------------------------------------
#<LibXML::XML::XPath::Object:0x000008153182c0>

As you can see, the list contains the XPath object self. I intentionally displayed it as a bullet list and an inspect after a horizontal line. As you can see, the last item does not have a bullet in front of it. But where does it come from? Am I missing something or is this a bug?

The return value for each is the result object itself. In your code, since you use = in the line <%= @projects.each do |pr| %> <%= @projects.each do |pr| %> , you print out each of the projects as a list item (in the block), and then print the return value from each .

The solution is just to use <% ... %> (ie no = ):

<ul>
<% @projects.each do |pr| %>
    <li><%= pr.first.content %></li>
<% end %>
</ul>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM