0
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.

2
  • 1
    isn't element.text enough? Commented May 25, 2014 at 7:04
  • Unfortunately not, the problem is the source XML file has hundreds of speakers with hundreds of speeches. The current code is creating the files properly but putting speeches from everyone in all the created XML files. Commented May 25, 2014 at 7:05

1 Answer 1

0

The xpath you are looking for is:

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

see XPath to select Element by attribute value

Sign up to request clarification or add additional context in comments.

8 Comments

This looks about right and I tried it before but it gives me an error: node.rb:159:in `evaluate': Invalid expression: //speech/speaking[@name=Mr. THOMAS] (Nokogiri::XML::XPath::SyntaxError)
Make sure you have enclosing quotes (/speech/speaking[@name='Mr. THOMAS'])
The above comment yields: speaking[@name=] (Nokogiri::XML::XPath::SyntaxError)
All I suggested was to make sure you enclosed the value with single quotes '...
It is enclosed. I feel that this is on the right track but I have been down this path and can not get it to work. I posted some sample XML above if you have any further ideas.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.