How to read and store XML data in database

微笑、不失礼 提交于 2019-12-25 04:46:10

问题


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:

  1. The Node names must be displayed in header postion in row wise one after the other

    Example:

    Column1, column2, column3.....
    
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!