使用Java解析XML值并插入到Postgresql中

使用Java解析XML值并插入到Postgresql中,java,jdbc,xml-parsing,saxparser,postgresql-9.2,Java,Jdbc,Xml Parsing,Saxparser,Postgresql 9.2,我读了很多关于堆栈溢出的文章,想知道我是否真的能找到解析XML文档并从中检索数据并将其插入到我的PostgreSQL数据库表中的方法,该表的列名与XML schema标记的列名完全相同,但我没能得到近似的场景。我有以下XML模式- <?xml version="1.0"> <request uuid = 'xyz'> <app hash='', name='', package = '', version='', filesize='',cr

我读了很多关于堆栈溢出的文章,想知道我是否真的能找到解析XML文档并从中检索数据并将其插入到我的PostgreSQL数据库表中的方法,该表的列名与XML schema标记的列名完全相同,但我没能得到近似的场景。我有以下XML模式-

<?xml version="1.0">
    <request uuid = 'xyz'>
        <app hash='', name='', package = '', version='', filesize='',create_date='', upate_date=''>
            <url>
                <name>---</name>
                <score>--</score>
            </url>
            <url>
                <name>---</name>
                <score>--</score>
            </url>
        </app>
    </request>

我需要学习一些东西,帮助我从上述给定的XML模式中插入这两个表中与其列相关的值(例如parse和insert)。我使用的是PostgreSQL 9.2版本,我需要使用JAVA

任何人如果能给我举个例子,说明如何解析单个XML文档并将其插入两个不同的表中,都会非常有帮助

提前谢谢你

更新


我们是否假设在这里使用SAX解析器进行解析和插入?请帮助我理解执行此插入的方法。

以下是使用JDOM插入应用程序值的代码:

Connection connection = DriverManager.getConnection("url");
File file = new File(fileURL);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document docDom = db.parse(file);
NodeList list = docDom.getElementsByTagName("app");
String appInsertForamt = "INSERT INTO app(%s) VALUES (%s);";
String[] attributes = { "hash", "name", "package", "version", "filesize", "create_date" };
String[] values = new String[attributes.length];
for (int i = 0; i < list.getLength(); i++) {
    NamedNodeMap map = list.item(i).getAttributes();
for (int j = 0; j < attributes.length; j++) {
    values[j] = map.getNamedItem(attributes[j]).toString().replaceFirst(".*=", "");
    }
    String cols = Arrays.toString(attributes).replaceAll("\\[|\\]", "");
    String vals = Arrays.toString(values).replaceAll("\\[|\\]", "");
    String query = String.format(appInsertForamt, cols, vals);
    Statement statement = connection.createStatement();
    statement.executeUpdate(query);
}
Connection-Connection=DriverManager.getConnection(“url”);
File File=新文件(fileURL);
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
DocumentBuilder db=dbf.newDocumentBuilder();
Document docDom=db.parse(文件);
NodeList list=docDom.getElementsByTagName(“应用”);
字符串appInsertForamt=“插入应用(%s)值(%s);”;
字符串[]属性={“哈希”、“名称”、“包”、“版本”、“文件大小”、“创建日期”};
字符串[]值=新字符串[attributes.length];
对于(int i=0;i
这是一个老问题,但我最近在读取XML和更新具有相同列名的postgresql时遇到了同样的问题。这是我编写的代码,对我来说很好。我很难找到解决方案,所以这可能会帮助人们

    public class readXmlToPostgres {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {

ArrayList<String> allcols = new ArrayList<String>();

allcols = getcolnames();
boolean hasvalue=false;
boolean colbool[] = new boolean[allcols.size()];
for(int i=0; i<allcols.size(); i++){
    colbool[i] = false; 
}


try {
    XMLInputFactory factory = XMLInputFactory.newInstance();
    XMLEventReader eventReader =
    factory.createXMLEventReader(
    new FileReader("path/to/xml/file"));
    String columnName = "";
    String columnValue="";
    String attrval="";
    String insertStatement_A = "";
    String insertStatement_B = "";
    String insertStatement_C="";
    String insertStatement_full="";
    boolean isnull = false;
    ArrayList<String> insertColnames = new ArrayList<String>();
    ArrayList<String> insertValues = new ArrayList<String>();
    Connection ds             = null;
    String dbName = "";

    ds = createConnection();

    int count = 0;
    while(eventReader.hasNext()){

        XMLEvent event = eventReader.nextEvent();
        switch(event.getEventType()){
        case XMLStreamConstants.START_ELEMENT:
        StartElement startElement = event.asStartElement();
        String qName = startElement.getName().getLocalPart();
        if (qName.equalsIgnoreCase("records")) {
        insertColnames.clear();
        insertValues.clear();

        insertStatement_A="insert into \"Tablename\"(";
        insertStatement_B=") values(";
        insertStatement_C=" )";
        insertStatement_full="";
    }

    for(int i=0; i<allcols.size(); i++)

    { if (qName.equalsIgnoreCase(allcols.get(i))) {
        colbool[i] = true;

        Iterator<Attribute> attributes = startElement.getAttributes();
        columnName = allcols.get(i);
        attrval="false";
        if(attributes.hasNext()){
        isnull = true;
        colbool[i] = false;
        columnName=allcols.get(i);
        columnValue=null;
        insertColnames.add(columnName);
        insertValues.add(columnValue);

    }

    }       
    }
    break;
    case XMLStreamConstants.CHARACTERS:
    Characters characters = event.asCharacters();
    for(int i=0; i<allcols.size(); i++){
    if(colbool[i]){



    columnName=allcols.get(i);
    columnValue=characters.getData();


    insertColnames.add(columnName);
    insertValues.add(columnValue);




    colbool[i] = false;




    }

    }
    break;
    case  XMLStreamConstants.END_ELEMENT:
    EndElement endElement = event.asEndElement();
    if(endElement.getName().getLocalPart().equalsIgnoreCase("records")){

    System.out.println(": "+count);
    count = count + 1;

    for(int a=0; a<2;a++){
    if((insertColnames.get(0).equals("Id")) || (insertColnames.get(0).equals("Type"))){
    insertColnames.remove(0);
    insertValues.remove(0);
    }
    }

    //make query
    for(int i=0; i<insertColnames.size(); i++){




    insertStatement_A += "\""+insertColnames.get(i)+"\", ";
    if(insertValues.get(i)==null){
    //   System.out.println("value is null");
    insertStatement_B += ""+insertValues.get(i)+", ";
    }
    else{
    //insertValues.get(i) = insertValues.get(i).replace("'", "");
    insertStatement_B += "'"+insertValues.get(i).replace("'", "")+"', ";
    }                               
    }//for end

    insertStatement_A=insertStatement_A.replaceAll(", $", "");

    insertStatement_B=insertStatement_B.replaceAll(", $", "");

    insertStatement_full = insertStatement_A + insertStatement_B + insertStatement_C;



    insertData(insertStatement_full, ds);


    }
    break;
    }           
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (XMLStreamException e) {
e.printStackTrace();
}
}


public static void insertData(String insertQuery, Connection ds) throws SQLException{
java.sql.Statement  stmt  = null;
stmt = ds.createStatement();

stmt.executeUpdate(insertQuery);


}


public static ArrayList<String> getcolnames() throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException{

ArrayList<String> allcols = new ArrayList<String>();
allcols.clear();

Connection ds             = null;
java.sql.Statement  stmt  = null;
String dbName = "";

ds = createConnection();
stmt = ds.createStatement();

String colQuery="SELECT column_name FROM information_schema.columns WHERE table_schema = 'public'  AND table_name   = 'tablename'";

ResultSet rs = stmt.executeQuery(colQuery);
while(rs.next()){

String colname=rs.getString("column_name");

allcols.add(colname);

System.out.println("column size : "+allcols.size());
return allcols;

}



public static Connection createConnection()
throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {
Connection         c;

String DbName = "Databasename";




Class.forName("org.postgresql.Driver");
c = DriverManager.getConnection("jdbc:postgresql://host/" + DbName , "user", "password");

System.out.println("connection established.");
return c;
}


}
公共类readXmlToPostgres{
publicstaticvoidmain(字符串[]args)抛出ClassNotFoundException、InstantiationException、IllegalAccessException、SQLException{
ArrayList allcols=新的ArrayList();
allcols=getcolnames();
布尔值=false;
boolean colbool[]=新布尔值[allcols.size()];

对于(inti=0;ii,最好将示例代码放在答案中,而不是放在外部链接中。这样,即使外部链接移动或消失,答案仍然会帮助人们。
Connection connection = DriverManager.getConnection("url");
File file = new File(fileURL);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document docDom = db.parse(file);
NodeList list = docDom.getElementsByTagName("app");
String appInsertForamt = "INSERT INTO app(%s) VALUES (%s);";
String[] attributes = { "hash", "name", "package", "version", "filesize", "create_date" };
String[] values = new String[attributes.length];
for (int i = 0; i < list.getLength(); i++) {
    NamedNodeMap map = list.item(i).getAttributes();
for (int j = 0; j < attributes.length; j++) {
    values[j] = map.getNamedItem(attributes[j]).toString().replaceFirst(".*=", "");
    }
    String cols = Arrays.toString(attributes).replaceAll("\\[|\\]", "");
    String vals = Arrays.toString(values).replaceAll("\\[|\\]", "");
    String query = String.format(appInsertForamt, cols, vals);
    Statement statement = connection.createStatement();
    statement.executeUpdate(query);
}
    public class readXmlToPostgres {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {

ArrayList<String> allcols = new ArrayList<String>();

allcols = getcolnames();
boolean hasvalue=false;
boolean colbool[] = new boolean[allcols.size()];
for(int i=0; i<allcols.size(); i++){
    colbool[i] = false; 
}


try {
    XMLInputFactory factory = XMLInputFactory.newInstance();
    XMLEventReader eventReader =
    factory.createXMLEventReader(
    new FileReader("path/to/xml/file"));
    String columnName = "";
    String columnValue="";
    String attrval="";
    String insertStatement_A = "";
    String insertStatement_B = "";
    String insertStatement_C="";
    String insertStatement_full="";
    boolean isnull = false;
    ArrayList<String> insertColnames = new ArrayList<String>();
    ArrayList<String> insertValues = new ArrayList<String>();
    Connection ds             = null;
    String dbName = "";

    ds = createConnection();

    int count = 0;
    while(eventReader.hasNext()){

        XMLEvent event = eventReader.nextEvent();
        switch(event.getEventType()){
        case XMLStreamConstants.START_ELEMENT:
        StartElement startElement = event.asStartElement();
        String qName = startElement.getName().getLocalPart();
        if (qName.equalsIgnoreCase("records")) {
        insertColnames.clear();
        insertValues.clear();

        insertStatement_A="insert into \"Tablename\"(";
        insertStatement_B=") values(";
        insertStatement_C=" )";
        insertStatement_full="";
    }

    for(int i=0; i<allcols.size(); i++)

    { if (qName.equalsIgnoreCase(allcols.get(i))) {
        colbool[i] = true;

        Iterator<Attribute> attributes = startElement.getAttributes();
        columnName = allcols.get(i);
        attrval="false";
        if(attributes.hasNext()){
        isnull = true;
        colbool[i] = false;
        columnName=allcols.get(i);
        columnValue=null;
        insertColnames.add(columnName);
        insertValues.add(columnValue);

    }

    }       
    }
    break;
    case XMLStreamConstants.CHARACTERS:
    Characters characters = event.asCharacters();
    for(int i=0; i<allcols.size(); i++){
    if(colbool[i]){



    columnName=allcols.get(i);
    columnValue=characters.getData();


    insertColnames.add(columnName);
    insertValues.add(columnValue);




    colbool[i] = false;




    }

    }
    break;
    case  XMLStreamConstants.END_ELEMENT:
    EndElement endElement = event.asEndElement();
    if(endElement.getName().getLocalPart().equalsIgnoreCase("records")){

    System.out.println(": "+count);
    count = count + 1;

    for(int a=0; a<2;a++){
    if((insertColnames.get(0).equals("Id")) || (insertColnames.get(0).equals("Type"))){
    insertColnames.remove(0);
    insertValues.remove(0);
    }
    }

    //make query
    for(int i=0; i<insertColnames.size(); i++){




    insertStatement_A += "\""+insertColnames.get(i)+"\", ";
    if(insertValues.get(i)==null){
    //   System.out.println("value is null");
    insertStatement_B += ""+insertValues.get(i)+", ";
    }
    else{
    //insertValues.get(i) = insertValues.get(i).replace("'", "");
    insertStatement_B += "'"+insertValues.get(i).replace("'", "")+"', ";
    }                               
    }//for end

    insertStatement_A=insertStatement_A.replaceAll(", $", "");

    insertStatement_B=insertStatement_B.replaceAll(", $", "");

    insertStatement_full = insertStatement_A + insertStatement_B + insertStatement_C;



    insertData(insertStatement_full, ds);


    }
    break;
    }           
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (XMLStreamException e) {
e.printStackTrace();
}
}


public static void insertData(String insertQuery, Connection ds) throws SQLException{
java.sql.Statement  stmt  = null;
stmt = ds.createStatement();

stmt.executeUpdate(insertQuery);


}


public static ArrayList<String> getcolnames() throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException{

ArrayList<String> allcols = new ArrayList<String>();
allcols.clear();

Connection ds             = null;
java.sql.Statement  stmt  = null;
String dbName = "";

ds = createConnection();
stmt = ds.createStatement();

String colQuery="SELECT column_name FROM information_schema.columns WHERE table_schema = 'public'  AND table_name   = 'tablename'";

ResultSet rs = stmt.executeQuery(colQuery);
while(rs.next()){

String colname=rs.getString("column_name");

allcols.add(colname);

System.out.println("column size : "+allcols.size());
return allcols;

}



public static Connection createConnection()
throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {
Connection         c;

String DbName = "Databasename";




Class.forName("org.postgresql.Driver");
c = DriverManager.getConnection("jdbc:postgresql://host/" + DbName , "user", "password");

System.out.println("connection established.");
return c;
}


}