Newbie question Modifying an XML file

New to Ruby and trying to do a find and replace in the
content of an XML file with Ruby and Nokogiri.

Below is an example of the XML.

<?xml version="1.0" encoding="ISO-8859-1"?> Type: POWERFORGED Piston-IndividualHigh comp.Powerforged0.9805" Pin Dia.2 Ring(s)5/64 Groove1 Ring(s)3/16 Groove1.735 CD.142 dish; DUROSHIELD® skirt coated piston; .060" Oversize8WL-2323F 60 Type: POWERFORGED Piston-IndividualHigh comp.Powerforged0.9805" Pin Dia.2 Ring(s)5/64 Groove1 Ring(s)3/16 Groove1.735 CD.142 dish; DUROSHIELD® skirt coated piston; .060" Oversize8WL-2323F 60 Type: POWERFORGED Piston-IndividualHigh comp.Powerforged0.9805" Pin Dia.2 Ring(s)5/64 Groove1 Ring(s)3/16 Groove1.735 CD.142 dish; DUROSHIELD® skirt coated piston; Standard Size8WL-2323F

The code below Just changes the 1st node instead of iterating through
each node and doing the find and replace.

require ‘rubygems’
require ‘nokogiri’

file_name = ‘Aces.xml’
@doc = Nokogiri::XML(File.open(file_name))
partName = @doc.at_css (“Part”)
partName.content = partName.content.gsub!(/L-/,‘L’)# removes L-
File.write(“ACESFixed.xml”, @doc.to_xml)

Thank you
Bob

Perfect.
Thank you.

Is there a way to nest the gsubs?

Hey Bob,

you need to use the ‘css’ method, instead of the ‘at_css’ method. The
difference is that ‘at_css’ only returns the first match.

In addition, you also need to iterate over the result set after you
change your code to use ‘css’.

Example:

################
parts = doc.css(‘Part’)

parts.each do |part|
part.content = part.content.gsub!(/L-/,‘L’)
end

File.write(“ACESFixed.xml”, @doc.to_xml)
################

Hope that helps :slight_smile: