0

I have been reading lot of post on Stack Overflow and was wondering if I could really find the way how can I parse XML document and retrieve the data from it and insert it into my PostgreSQL database table which have exact column name as the XML schema tag have, but I failed to get the approx scenario. I have a following XML schema-

<?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>

and have two tables in PostgreSQL database name "app" and "url" shown below:

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

and

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


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

I needed to learn something that helps me insert the values inside these two tables with respect to their column ( example parse and insert) from the above given XML schema. I am using a PostgreSQL 9.2 version and I needed to do it using JAVA.

Anyone who could provide me a example of how should I parse the single XML document and have it inserted into two different tables would be really helpful.

Thank you in advance!

UPDATE

Do we suppose to use SAX parser here for parsing and insert likewise? Please help me understand the method to do this insertion.

4

2 に答える 2

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 ステートメントを作成して、最後にデータベースを更新します。

于 2017-03-31T12:05:55.483 に答える