what's wrong with following code?

18 views
Skip to first unread message

Dec

unread,
Jun 16, 2011, 10:49:03 AM6/16/11
to nokogiri-talk
====
require 'nokogiri'
xml = Nokogiri::XML("<a><b><c>Test 1</c></b><b><c>Test 2</c></
b><b><c>Test 3</b></c></a>")

xml.search("//b").each do |b|
b.at("//c").content = b.at("//c").content + " B"
end
puts xml

====

I'm expecting to get "B" appended to each <c> element, but get output
like this:
======
<?xml version="1.0"?>
<a>
<b>
<c>Test 1 B B B</c>
</b>
<b>
<c>Test 2</c>
</b>
<b>
<c>Test 3</c>
</b>
</a>
===============

Mike Dalessio

unread,
Jun 16, 2011, 12:04:20 PM6/16/11
to nokogi...@googlegroups.com
Hello,

In Xpath, a initial slash in your search string says "start at the top of the document." You want to start at the context node, so use "./" like so:

    xml.search("//b").each do |b|
      b.at("./c").content = b.at("./c").content + " B"
    end

Or save the extra XPath query and write:

    xml.search("//b").each do |b|
      b.at("./c").content += " B"
    end

---
mike dalessio / @flavorjones

Reply all
Reply to author
Forward
0 new messages