Reputation: 283
Hey everyone I was would greatly appreciate some help here, I am trying to parse an XML and put the results into a database for an app I am working on(Phonegap/JQuery mobile app). Can someone show me how to do this inside of a JS function?
I understand the parsing process for the XML however I am a little lost on storing it locally into the SQLlite database that phonegap lets you access. Here is the XML I am using:
<?xml version="1.0" encoding="UTF-8"?>
<orders>
<order>
<orderId>123456789</orderId>
<city>Cincinnati</city>
<state>Ohio</state>
<zip>45451</zip>
</order>
</orders>
Here is a JS function to parse this:
$(document).ready(function(){
$.ajax({
type: "GET",
url: "testOrders.xml",
dataType: "xml",
success: function(xml) {
$(xml).find('order').each(function(){
orderId = $(this).find("orderId").text();
city = $(this).find("city").text();
state = $(this).find("state").text();
zip = $(this).find("zip").text();
$("#acceptedOrdersContent").append('<div>');
$("#acceptedOrdersContent").append('<h3>'OrderId: '+ orderId + '</h3>');
$("#acceptedOrdersContent").append('<p>');
$("#acceptedOrdersContent").append('City: '+ city + '<br />');
$("#acceptedOrdersContent").append('State: '+ state + '<br />');
$("#acceptedOrdersContent").append('Zip: '+ zip +'<br />');
$("#acceptedOrdersContent").append('</p>');
$("#acceptedOrdersContent").append('</div>');
});
}
});
});
Thanks everyone!
Upvotes: 1
Views: 2517
Reputation: 300
Create the DB:
var db = openDatabase('PhoneGap_db', '1.0', '', 2 * 1024 * 1024);
Create the table:
db.transaction(function (tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS orders (id unique, city, state, zip)');
});
Insert into table:
db.transaction(function (tx) {
tx.executeSql('INSERT INTO orders (id, city, state, zip) VALUES (orderId,city,state,zip)');
});
it will be best to put the INSERT inside the AJAX's callback:
$.ajax({
type: "GET",
url: "testOrders.xml",
dataType: "xml",
success: function(xml) {
$(xml).find('order').each(function(){
orderId = $(this).find("orderId").text();
city = $(this).find("city").text();
state = $(this).find("state").text();
zip = $(this).find("zip").text();
db.transaction(function (tx) {
tx.executeSql('INSERT INTO orders (id, city, state, zip) VALUES (orderId,city,state,zip)');
});
});
}
});
Good luck!
Upvotes: 5