【问题标题】:Parse XML values and insert into Postgresql using Java使用 Java 解析 XML 值并插入 Postgresql
【发布时间】:2013-07-09 19:07:20
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      这是一个老问题,但我最近在读取 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并获取所需列的值,为您创建一个插入语句,最后更新您的数据库。

      【讨论】:

      • 最好将示例代码放在答案中,而不是外部链接。那么即使外部链接移动或消失,答案仍然会对人们有所帮助。
      猜你喜欢
      • 2012-12-18
      • 2012-10-10
      • 2015-06-22
      • 1970-01-01
      • 2012-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-26
      相关资源
      最近更新 更多