jeudi 10 septembre 2015

parse xml using nokogiri rails to compare a database table

I have a table called users

users table have three columns:

id, ref, name

I want to parse the following XML document using nokogiri and list out the matched and unmatched records by comparing the values into the users table records

<?xml version="1.0" encoding="UTF-8"?>
<EXPORT>
  <DETAIL>
    <ID>150</ID>
    <REF>188440</REF>
    <USER>Bruce</USER>
  </DETAIL>
    <DETAIL>
    <ID>1501003</ID>
    <REF>1884402</REF>
    <USER>Alice</USER>
  </DETAIL>
</EXPORT>

Ex:

Users.where(id: 1501003).name
Users.where(ref: 188440).name

find the name by comparing the id and ref.

Note: if Id does not match, then compare with ref. If Id matches then ignore ref.

What I tried:

doc = Nokogiri::XML(File.open(self.filename))
exp = "//EXPORT/DETAIL"

NODES = doc.xpath(exp)

nodes.each do |node|
  unless node.text.nil?
    User.where(id: node.text).first.name
end

Aucun commentaire:

Enregistrer un commentaire