Reputation: 1033
I receive the following xml in a database field.
<Request type="Final">
<Field name="Grade">94.5</Field>
<Field name="EmployeeName">2398;;;Mike5</Field>
<Field name="Date">051215</Field>
</Request>
Currently, I just receive it and display them as it is:
def request_xml
(request.blank? ? "" : request.message)
end
Now, I want to return the xml by stripping of the EmployeeName value to nil i.e 2398;;;Mike5 from 2398;;;Mike5 based on certain logic
So I am ok with 2 solutions
> 1. if EmployeeName value matches a regex, return null else return the value as it is?
> - Return <Field name="EmployeeName"></Field>
> 2. if EmployeeName value matches a regex completely strip out the whole EmployeeName XML: <Field
> name="EmployeeName">2398;;;Mike5</Field> from the result
Is either of the above solution possible via ruby/rails code?
Upvotes: 1
Views: 85
Reputation: 7482
As @asiniy already answered, you can use nokogiri
for changing your xml, like this:
UPDATE: you can filter tag contents with the following code:
require 'nokogiri'
xml = Nokogiri::XML('<Request type="Final">
<Field name="Grade">94.5</Field>
<Field name="EmployeeName">2398;;;Mike5</Field>
<Field name="Date">051215</Field>
</Request>')
# remove all Employee elements, containing text 2398
xml.css('Field[name=EmployeeName]').select { |node| node.text =~ /2398/ }.map(&:remove)
puts xml
will output
<?xml version="1.0"?>
<Request type="Final">
<Field name="Grade">94.5</Field>
<Field name="Date">051215</Field>
</Request>
Upvotes: 1
Reputation: 15156
You can do it through nokogiri gem. Here is official tutorial
require 'nokogiri'
xml = Nokogiri::XML('<Request type="Final">
<Field name="Grade">94.5</Field>
<Field name="EmployeeName">2398;;;Mike5</Field>
<Field name="Date">051215</Field>
</Request>')
if xml.xpath('//EmployeeName')
do_whatever_you_want
Upvotes: 0