rubyxmlnokogiribuilderrexml

Ruby XML Reading from one XML and parsing into another


XPath.each( xmldoc, "//speech/speaking") do |element| 
# puts element.attributes['name']
# puts element.text
File.open(file_name + "_" + element.attributes['name'] + "-" + year + ".xml", 'a+') do |f|
    f.write("<speaker>" + element.attributes['name'] + "</speaker>")
    f.write("<speech>" + doc.xpath('//speech/speaking').text + "</speech>" + "\n")
end
end

Hello stackoverflow I am looking for help solving a logic issue I am having with XML files. The above code creates a file with the "speakers" name and then it should place what the speaker says into that file.

The problem that I am running into is that it places ALL of the speakers into the same file. So I am thinking the problem lies here:

f.write("<speech>" + doc.xpath('//speech/speaking').text + "</speech>" + "\n")

I am hoping that someone has a better way of doing this, but the idea would be to change the above code to:

doc.xpath('//speech/speaking').text WHERE speaker == element.attributes['name']

Ultimately I would like to have each speaker in their own XML file with their own speeches.

<speaking name="Mr. FAZIO">I appreciate my friend yielding.</speaking>

The above is a sample from the XML file.


Solution

  • The xpath you are looking for is:

    doc.xpath("//speech/speaking[@name='#{element.attributes['name']}']").text
    

    see XPath to select Element by attribute value