0

我一直在阅读 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 解析器进行解析和插入?请帮助我了解进行此插入的方法。

4

2 回答 2

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);
}
于 2013-08-27T11:55:59.970 回答
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 并获取所需列的值,为您创建一个插入语句,最后更新您的数据库。

于 2017-03-31T12:05:55.483 回答