zspace
zspace

Reputation: 41

How do I add a node attribute in XML using Nokogiri?

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.

Upvotes: 1

Views: 1537

Answers (1)

the Tin Man
the Tin Man

Reputation: 160551

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>

Upvotes: 1

Related Questions