2012-10-11 42 views
0

我想將xml解析到mysql表中我能夠解析xml但我不熟悉mysql。 有什麼想法?提前致謝。在java中解析xml到mysql

+------+------+ 
|drinks|stater| 
+------+------+ 
|some |some | 
+------+------+ 
|some |some | 
+------+------+ 

我想要結果是什麼的例子。 xml文件的 例如:

<?xml version="1.0"?> 
<food> 
    <menu> 
     <drinks>some drinks</drink> 
     <starter>some food</starter> 
     <main>more food</main> 
     <dessert>more food/dessert> 
    </menu> 
    <menu> 
     <drinks>some drinks</drink> 
     <starter>some food</starter> 
     <main>more food</main> 
     <dessert>more food/dessert> 
    </menu> 
</food> 

到目前爲止,這是我所

public class xmlToMySql extends DefaultHandler { 

public static void main(String argv[]){ 

    try { 

    SAXParserFactory factory = SAXParserFactory.newInstance(); 
    SAXParser saxParser = factory.newSAXParser(); 

    DefaultHandler handler = new DefaultHandler() { 

    boolean drinks = false; 
    boolean starter = false; 

    public void startElement(String uri, String localName,String qName, 
       Attributes attributes) throws SAXException { 

     if (qName.equalsIgnoreCase("DRINKS")) { 
      drinks = true; 

     } 

     if (qName.equalsIgnoreCase("STARTER")) { 
      starter = true; 
     } 

    } 

    public void characters(char ch[], int start, int length) throws SAXException { 

     if (drinks) { 
      String hnName = new String(ch,start,length); 
      drinks = false; 

     } 
     if (starter) { 
      String ptStr = new String(ch,start,length); 
      starter = false; 
     } 
    } 
    }; 

     saxParser.parse("someXmlFile.xml", handler); 

    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 

} 

回答

1

使用MySQL XML功能

ExtractValue() Extracts a value from an XML string using XPath notation 
UpdateXML()  Return replaced XML fragment 

下面是一個例子:

mysql> SET @xml = '<a><b>X</b><b>Y</b></a>'; 
Query OK, 0 rows affected (0.00 sec) 

mysql> SET @i =1, @j = 2; 
Query OK, 0 rows affected (0.00 sec) 

mysql> SELECT @i, ExtractValue(@xml, '//b[[email protected]]'); 
+------+--------------------------------+ 
| @i | ExtractValue(@xml, '//b[[email protected]]') | 
+------+--------------------------------+ 
| 1 | X        | 
+------+--------------------------------+ 
1 row in set (0.00 sec) 

找到完整的參考here

+0

這有助於感謝負荷。 – user1646537

0

如果您解析值並可以將其存儲到變量中,然後使用下面的Java代碼

Class.forName("com.mysql.jdbc.Driver"); 
String connectionString="jdbc:mysql://localhost:3306/DbName"; 
Connection connection = DriverManager.getConnection(connectionString,username,password); 

PreparedStatement pst; 
ResultSet rs; 
while(number of entries you want to enter) 
{ 
    pst=connection.prepareStatement("insert into tablename values(?,?)"); 
    pst.setString(1,drinks); 
    pst.setString(2,starter); 
    pst.executeUpdate(); 
}