问题
I am very new joiner in java and xml parser, I need to read data from an XMl file and store it in database.
Firstly what I did is I have read data from an Xml fileand will store in in text file in Column and row format. Can any one please tell me how can read data from an xml file and manipulate data in form of column and rows.
Column and rows means:
The Node names must be displayed in header postion in row wise one after the other
Example:
Column1, column2, column3.....The values in that data must be stored in the above columns wise tags
Example:
Column1, column2, column3,... row1, row2, row3,... row1, row2, row3,....
Please help me, I am fight with this from past 10 days, I am unable to read data in column and row wise. What I have done is:
Sample code:
public class XMLReader extends XMLUtil{
public static void main(String args[]) {
try{
XMLUtil xml=new XMLUtil();
Document doc=xml.docFromFilePath("data/Schools.xml");
//System.out.println("Root element :"+ doc.getDocumentElement().getNodeName());
NodeList nl= doc.getElementsByTagName("*");
for(int i=0;i< nl.getLength();i++)
{
/*String column1=nl.item(i).getNodeName();
String column=nl.item(i).getFirstChild().getNodeValue();
System.out.println(column1+":"+ column);*/
Node n = nl.item(i);
String name=n.getNodeName();
System.out.print(name+ " ");
}
System.out.println();
File f=new File("results/test1.txt");
xml.prettyPrintToFile(f, doc);
FileUtil futil=new FileUtil();
futil.readFileBytes(f);
//System.out.println(futil.toString());
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
回答1:
In order to form a query you should use PreparedStatement.
A sample usage:
String query = "INSERT INTO some_table (col1,col2,col3) values (?,?,?)
PreparedStatement stmt = null;
stmt = con.prepareStatement(query);
//now use the values from the xml and bind them to the statement
stmt.setString(someStringValue);
stmt.setInt(someIntValue);
...
stmt.execute();
来源:https://stackoverflow.com/questions/11611390/how-to-read-and-store-xml-data-in-database