How to import xml into a database by using JAVA

Source: Internet
Author: User

How to import xml into a database by using JAVA

We know that there are many ways to import data into the database by inserting data into the database by importing xml into the database. In the past, the most commonly used method was to insert a piece of data through SQL statements, today, we will learn to add the data in xml to the database once:

First, write an xml file:

<?xml version="1.0" encoding="utf-8"?><ACCESOS>    <item>       <SOCIO>           <NUMERO>00045050</NUMERO>           <REPOSICION>0</REPOSICION>           <NOMBRE>MOISES MORENO</NOMBRE>           <TURNOS>                <LU>T1</LU>                <MA>T2</MA>                <MI>T3</MI>                <JU>T4</JU>                <VI>T5</VI>                <SA>T6</SA>                <DO>T7</DO>           </TURNOS>        </SOCIO>    </item>    <item>         <SOCIO>               <NUMERO>00045051</NUMERO>               <REPOSICION>0</REPOSICION>               <NOMBRE>RUTH PENA</NOMBRE>               <TURNOS>                    <LU>S1</LU>                    <MA>S2</MA>                    <MI>S3</MI>                    <JU>S4</JU>                    <VI>S5</VI>                    <SA>S6</SA>                    <DO>S7</DO>               </TURNOS>          </SOCIO>         </item></ACCESOS>

Then write the method to read the xml file: Introduce the dom4j jar package to lib under WEB-INFO and add references:

Import org. dom4j. document; import org. dom4j. element; import org. dom4j. io. SAXReader; public static void main (String [] args) {// SQL statement for data insertion String SQL = "insert into T_XML (NUMERO, REPOSICION, NOMBRE, TURNOS) values (?, ?, ?, ?) "; Connection conn = null; PreparedStatement pstmt = null; try {conn = DbUtil. getConnection (); pstmt = conn. prepareStatement (SQL); // read the xml file Document doc = new SAXReader (). read (new File ("F:/J2EEmyself/DRP/test_xmlImport/xml/test01.XML"); // select the node List itemList = doc for the xml File. selectNodes ("ACCESOS/item/SOCIO"); // traverses the nodes in the read xml for (Iterator iter = itemList. iterator (); iter. hasNext ();) {Element el = (Element) iter. next (); // read the node content String numero = el. elementText ("NUMERO"); String reposicion = el. elementText ("REPOSICION"); String nombre = el. elementText ("NOMBRE"); // traverses the List of turnosList = el. elements ("TURNOS"); StringBuffer sbString = new StringBuffer (); for (Iterator iter1 = turnosList. iterator (); iter1.hasNext ();) {Element turnosElt = (Element) iter1.next (); String lu = turnosElt. elementText ("LU"); String ma = turnosElt. elementText ("MA"); String mi = turnosElt. elementText ("MI"); String ju = turnosElt. elementText ("JU"); String vi = turnosElt. elementText ("VI"); String sa = turnosElt. elementText ("SA"); String doo = turnosElt. elementText ("DO"); sbString. append (lu + "," + ma + "," + mi + "," + ju + "," + vi + "," + sa + ", "+ doo);} // assign pstmt to the SQL statement. setString (1, numero); pstmt. setString (2, reposicion); pstmt. setString (3, nombre); pstmt. setString (4, sbString. toString (); pstmt. addBatch ();} pstmt.exe cuteBatch (); System. out. print ("succeeded in importing XML into the database");} catch (Exception e) {e. printStackTrace ();} finally {DbUtil. close (pstmt); DbUtil. close (conn );}}

This is easy to read the data in the xml file to the database: results in the database:

 

In fact, it is very easy to read the data in xml into the database, as long as the data in each node can be traversed cyclically.



How does java add parsed xml data to the database?

You can use SAXParser and Document to parse XML and splice the obtained data into SQL statements and insert them into the database.
Example: public class ReaderXML extends DefaultHandler {
@ Override
Public void startElement (String uri, String localName, String qName, Attributes attributes) throws SAXException {
// QName node name
// Cyclic node attributes
String SQL = null;
For (int I = 0; I <attributes. getLength (); I ++ ){
Attributes. getQName (I); // attribute name
Attributes. getValue (I); // Attribute Value
SQL = "insert into..."; // concatenate SQL statements to insert data.
//.....
}
}
}

// Call
ReaderXML r = new ReaderXML (); SAXParserFactory. newInstance (). newSAXParser (). parse (getClass (). getResourceAsStream ("data. xml"), r );

How to use java to parse xml documents and store data in the database

Package test11;
Import javax. xml. parsers .*;
Import org. w3c. dom .*;

Import java. io .*;
Public class XMLUtil
{
// This method is used to extract a specific class name from the XML configuration file and return an Instance Object
Public static Object getBean ()
{
Try
{
// Create a Document Object
DocumentBuilderFactory dFactory = DocumentBuilderFactory. newInstance ();
DocumentBuilder builder = dFactory. newDocumentBuilder ();
Document doc;
Doc = builder. parse (new File ("config. xml "));

// Obtain the text node containing the class name
NodeList nl = doc. getElementsByTagName ("className ");
Node classNode = nl. item (0). getFirstChild ();
String cName = classNode. getNodeValue ();

// Generate an Instance Object using the class name and return it
Class c = Class. forName (cName );
Object obj = c. newInstance ();
Return obj;
}
Catch (Exception e)
{
E. printStackTrace ();
Return null;
}
}
}

<? Xml version = "1.0"?>
<Config>
<ClassName> test11.CatAdapter </className>
</Config>
Then you can resolve the processed values to an array, LIST, or other objects that you can store. Just insert the SQL statement into the database. Major Database Transaction processing or batch processing

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.