Search code examples
rubyxpatherblibxml2

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?


Solution

  • The return value for each is the result object itself. In your code, since you use = in the line <%= @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 <% ... %> (i.e. no =):

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