posts - 28,comments - 3,trackbacks - 0

<?xml version="1.0" encoding="utf-8"?>
<Stoke>
 <Name ID="1" Type="VarChar" Length="10" Index="True">Ada</Name>
 <Sex ID="2" Type="VarChar" Length="2">female</Sex>
 <Age ID="3" Type="Integer">21</Age>
 <Comm>
  <Mobile ID="4" Type="VarChar" Length="15">13300008888</Mobile>
  <Email ID="5" Type="VarChar" Length="30">Ada@gmail.com</Email>
 </Comm>
</Stoke>

将上面的xml描述在数据库中创建一张表

import java.io.*;
import java.sql.*;
import java.util.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;

public class XmlToSql
{
 public static void getNode(NodeList nl,StringBuffer sql)
 {
  for(int i=0;i<nl.getLength();i++)
  {
   Node node = nl.item(i);
   if(node.getNodeType() == Node.ELEMENT_NODE)
   {
    if(node.hasAttributes())
    {
     sql.append(node.getNodeName()+" ");
     NamedNodeMap attr = node.getAttributes();
     sql.append(attr.getNamedItem("Type").getNodeValue());
     if(attr.getNamedItem("Length")!=null)
     {
      sql.append("("+attr.getNamedItem("Length").getNodeValue()+")");
     }    
     sql.append(",");
     if(attr.getNamedItem("Index")!=null && attr.getNamedItem("Index").getNodeValue().equals("True"))
     {
      sql.append("index index_"+node.getNodeName()+"("+node.getNodeName()+"),");
     }
    }
    else
    {
     getNode(node.getChildNodes(),sql);
    }       
   }
  }
 }
 
 public static void main(String[] args)
 {
  try
  {
   DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
   DocumentBuilder builder = fac.newDocumentBuilder();
   Document document = builder.parse(new File("Data.xml"));
   
   Node node = document.getFirstChild();
   
   StringBuffer sql = new StringBuffer("create table temp(id int(11) NOT NULL auto_increment,");
   getNode(node.getChildNodes(),sql);
   sql.append("PRIMARY KEY  (id))");
   
   Class.forName("com.mysql.jdbc.Driver");
   String url ="jdbc:mysql://localhost/test";
   Connection conn= DriverManager.getConnection(url,"root","root");
   Statement stmt = conn.createStatement();
   stmt.execute(sql.toString());
  }
  catch(Exception e){
   e.printStackTrace();
  }
 } 
}

posted on 2006-11-29 11:38 李大嘴 阅读(205) 评论(0)  编辑  收藏

只有注册用户登录后才能发表评论。


网站导航: