1

I'm using Ruby 1.8.7 for a project.

I need to be able to parse and modify bits of XML code for it, and I'm running into a few problems. I am using Nokogiri to do the parsing.

I have the line:

<linking-phrase-appearance id="1JDLZ0609-JFP4ZP-TH" x="346" y="207" width="39" height="14"/>

I need to change it to:

<linking-phrase-appearance id="1JDLZ0609-JFP4ZP-TH" x="346" y="207" width="39" height="14" font-color="255 0 0 255"/>

I have code that finds the right lines to change, but when I change it nothing is written out to the output file.

This is the code I use to change the attribute:

# middle_node = id of line that needs to be changed (is unique to the line)
appearance = @xml.xpath("/xmlns:cmap/xmlns:map/xmlns:linking-phrase-appearance-list")
   appearance.each do |node|
      if node['id'] == middle_node
         node['font-color'] = '255,0,0,255'
       end
   end 

I assume there is some reason why this is not working but I'm unsure as to why.

2
  • 1
    Please add to your XML example showing the nodes from the root to your target node. We don't need everything, just enough to see that path and the questionable XMLNS. Commented May 2, 2011 at 2:31
  • I'm having issues with adding element attributes with node['<key>'] = '<value>' too node.set_attribute('<key>', '<value>') seems to be working better but still havent got it to actually work outside of my irb console yet. Commented Mar 2, 2016 at 21:46

1 Answer 1

1

One thing I see that could be wrong in your code, or could be because your examples are not good enough, is that you are using a XML namespace in your XPath, but the tag itself does not have a namespace.

This sample code shows that you're on the right track. I think your XPath is wrong, but without more of the XML document I can't know for sure:

require "nokogiri"

xml = '<xml><linking-phrase-appearance id="1JDLZ0609-JFP4ZP-TH" x="346" y="207" width="39" height="14"/></xml>'

target_id = '1JDLZ0609-JFP4ZP-TH'

doc = Nokogiri::XML(xml)
doc.search(%Q{//linking-phrase-appearance[@id="#{ target_id }"]}).each do |n|
  n['font-color'] = '255,0,0,255'
end
puts doc.to_xml

>> <?xml version="1.0"?>
>> <xml>
>>   <linking-phrase-appearance id="1JDLZ0609-JFP4ZP-TH" x="346" y="207" width="39" height="14" font-color="255,0,0,255"/>
>> </xml>
Sign up to request clarification or add additional context in comments.

Comments

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.