解析XML值并使用Java插入Postgresql

时间:2013-07-09 19:07:20

标签: java jdbc xml-parsing saxparser postgresql-9.2

我一直在阅读很多关于Stack Overflow的文章,并想知道我是否真的能找到解析XML文档并从中检索数据并将其插入到具有精确列名的PostgreSQL数据库表中的方法。 XML模式标签有,但我没有得到大约的情况。我有一个以下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>

并在PostgreSQL数据库名称“app”和“url”中有两个表如下所示:

app
-----------------------------
appid(serial) | hash | name | package | version | filesize | create_date | update_date

url
--------------------
urlid(serial) | name | score


Note: urlid & appid are made as Primary Key in both the tables.

我需要学习一些东西,这些东西可以帮助我根据上面给出的XML模式在这两个表中插入值(例如解析和插入)。我正在使用PostgreSQL 9.2版本,我需要使用JAVA。

任何能够为我提供如何解析单个XML文档并将其插入两个不同表格的示例的人都会非常有帮助。

提前谢谢!

更新

我们是否假设在此使用SAX解析器进行解析并同样插入?请帮我理解插入的方法。

2 个答案:

答案 0 :(得分:0)

这是使用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);
}

答案 1 :(得分:0)

这是一个老问题,但我最近在阅读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;
}


}

1:它使用StAX读取xml 2:它从数据库中获取列名 3:读取xml并获取所需列的值,为您创建一个insert语句,最后更新数据库。