I'll get folders that contain XML code. I need to put all that code into a database so I need an algorithm that parses XML into SQL.
private static void parseXml(String xml) {
Document doc = Jsoup.parse(xml);
StringBuilder queryBuilder;
StringBuilder columnNames;
StringBuilder values;
for (Element row : doc.select("row")) {
// Start the query
queryBuilder = new StringBuilder("insert into customer(");
columnNames = new StringBuilder();
values = new StringBuilder();
for (int x = 0; x < row.children().size(); x++) {
// Append the column name and it's value
columnNames.append(row.children().get(x).tagName());
values.append(row.children().get(x).text());
if (x != row.children().size() - 1) {
// If this is not the last item, append a comma
columnNames.append(",");
values.append(",");
}
else {
// Otherwise, add the closing paranthesis
columnNames.append(")");
values.append(")");
}
}
// Add the column names and values to the query
queryBuilder.append(columnNames);
queryBuilder.append(" values(");
queryBuilder.append(values);
// Print the query
System.out.println(queryBuilder);
}
}
INPUT:
<Customers>
<row>
<CustId>1</CustId>
<Name>Woodworks</Name>
<City>Baltimore</City>
</row>
<row>
<CustId>2</CustId>
<Name>Software Solutions</Name>
<City>Boston</City>
</row>
<row>
<CustId>3</CustId>
<Name>Food Fantasies</Name>
<City>New York</City>
</row>
</Customers>
OUTPUT:
insert into customer(custid,name,city) values(1,Woodworks,Baltimore)
insert into customer(custid,name,city) values(2,Software Solutions,Boston)
insert into customer(custid,name,city) values(3,Food Fantasies,New York)
The problem with this code is hardcoded to work just for that format. I need an algorithm that is generic so it can run any xml code and extract data. So far I don't know the format of xml files i ll get.
Can you help me to build an algorithm that can give me SQL statements for any XML file? Thank you.