如题,我的XML文档如下,要将下列字段得到然后导入数据库,我现在自己做主要是时间那个字符串老是取不全,我的代码也附在这里吧,如果代码可用,我再送他100分
<DATA>
<TABLE tableName="user02">
<USERID>1000000001</USERID>
<CREATEDATE>2007-02-11 00:00:00.0</CREATEDATE>
<CRTBY>012011</CRTBY>
<MODIFYDATE>null</MODIFYDATE>
<LSTMODBY>null</LSTMODBY>
<CMT>0</CMT>
<CMTUSER>null</CMTUSER>
<CMTDATE>null</CMTDATE>
<APPSTATUS>0</APPSTATUS>
<REMARK>921176</REMARK>
<ISNEW>1</ISNEW>
<LASTUPDATE>2007-04-28 10:58:00.0</LASTUPDATE>
</TABLE>
</DATA>
我的代码,其中dbcon是个封装了数据库访问的类,大家不要管它
public class SAXReader extends DefaultHandler{
dbcon connect = new dbcon();
String columnValue = null;
String tableName = null;
String columnName = null;
String sql = "insert into " ;
public void startDocument() throws SAXException {
}
public void processingInstruction(String taget, String data) throws SAXException {
}
public void startElement(String uri, String localName, String qName, Attributes attr) throws SAXException {
if("TABLE".equals(qName))
{
for(int i = 0;i<attr.getLength();i++)
{
tableName = attr.getValue(i);
}
sql += tableName + " values(";
}
else
{
columnName = qName;
}
}
public void characters(char[] ch, int start, int length) throws SAXException {
columnValue=new String(ch,start,length).toString().trim();
if("".equals(columnValue))
{
columnValue = "''";
}
else
{
if(!"null".equals(columnValue)&&!"NULL".equals(columnValue)&&columnValue!=null)
{
columnValue = "'"+ columnValue+"'";
}
}
if(columnName!=null&&columnName.indexOf("DATE")>0)
System.out.println(columnValue);
}
public void endElement(String uri, String localName, String qName) throws SAXException {
if(!"DATA".equals(qName)&&!"TABLE".equals(qName))
{
if(!"LASTUPDATE".equals(columnName))
{
sql += columnValue +",";
}
if("LASTUPDATE".equals(columnName))
{
sql += columnValue;
}
}
columnName = null;
columnValue = null;
if("TABLE".equals(qName))
{
sql += ")";
System.out.println(sql);
insert(sql);
sql = "insert into ";
}
}
public void endDocument() throws SAXException {
}
public int insert(String sql)
{
int i = 0;
if(connect!=null)
{
i = connect.executeUpdate(sql);
}
return i ;
}
<DATA>
<TABLE tableName="user02">
<USERID>1000000001</USERID>
<CREATEDATE>2007-02-11 00:00:00.0</CREATEDATE>
<CRTBY>012011</CRTBY>
<MODIFYDATE>null</MODIFYDATE>
<LSTMODBY>null</LSTMODBY>
<CMT>0</CMT>
<CMTUSER>null</CMTUSER>
<CMTDATE>null</CMTDATE>
<APPSTATUS>0</APPSTATUS>
<REMARK>921176</REMARK>
<ISNEW>1</ISNEW>
<LASTUPDATE>2007-04-28 10:58:00.0</LASTUPDATE>
</TABLE>
</DATA>
我的代码,其中dbcon是个封装了数据库访问的类,大家不要管它
public class SAXReader extends DefaultHandler{
dbcon connect = new dbcon();
String columnValue = null;
String tableName = null;
String columnName = null;
String sql = "insert into " ;
public void startDocument() throws SAXException {
}
public void processingInstruction(String taget, String data) throws SAXException {
}
public void startElement(String uri, String localName, String qName, Attributes attr) throws SAXException {
if("TABLE".equals(qName))
{
for(int i = 0;i<attr.getLength();i++)
{
tableName = attr.getValue(i);
}
sql += tableName + " values(";
}
else
{
columnName = qName;
}
}
public void characters(char[] ch, int start, int length) throws SAXException {
columnValue=new String(ch,start,length).toString().trim();
if("".equals(columnValue))
{
columnValue = "''";
}
else
{
if(!"null".equals(columnValue)&&!"NULL".equals(columnValue)&&columnValue!=null)
{
columnValue = "'"+ columnValue+"'";
}
}
if(columnName!=null&&columnName.indexOf("DATE")>0)
System.out.println(columnValue);
}
public void endElement(String uri, String localName, String qName) throws SAXException {
if(!"DATA".equals(qName)&&!"TABLE".equals(qName))
{
if(!"LASTUPDATE".equals(columnName))
{
sql += columnValue +",";
}
if("LASTUPDATE".equals(columnName))
{
sql += columnValue;
}
}
columnName = null;
columnValue = null;
if("TABLE".equals(qName))
{
sql += ")";
System.out.println(sql);
insert(sql);
sql = "insert into ";
}
}
public void endDocument() throws SAXException {
}
public int insert(String sql)
{
int i = 0;
if(connect!=null)
{
i = connect.executeUpdate(sql);
}
return i ;
}
--
内存溢出和JDOM/DOM4J没有任何关系,要么你的JAVA虚拟机内存设的不够大,要么你代码有问题我不看你的代码了大概思路如下 用循环插入 在循环里面取字段 至于解析XML方式网上一大堆 本人习惯用DOM4J
import java.io.*;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
/**
*
* @author shu
*/
public class XMLReader {
/** Creates a new instance of XMLReader */
public XMLReader() {
}
public static void main(String args[]) throws Exception{
File file = new File("c:\\test.xml");
SAXReader reader = new SAXReader();
Document doc = reader.read(file);
Element root = doc.getRootElement();
java.util.Iterator it = root.elementIterator("TABLE");
Element foo;
while (it.hasNext()){
foo = (Element)it.next();
System.out.print("USERID:" + foo.elementText("USERID"));
System.out.println("CREATEDATE:" + foo.elementText("CREATEDATE"));
//这里加上你自己的插入数据库代码就OK
}
}
}
import java.sql.*;
import java.util.*;
import org.jdom.*;
import org.jdom.input.*;public class jiexiXML {
public jiexiXML() {
} public static void main(String[] args) throws Exception {
jieya.unZIP();
String file="d:/bbb.xml";
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance();
String url ="jdbc:microsoft:sqlserver://localhost:1433;databaseName=IPSNET;selectMethod=cursor;";
Connection conn = DriverManager.getConnection(url, "sa", "sa");
SAXBuilder sb = new SAXBuilder();
Document doc = sb.build(new FileInputStream(file));
Element root = doc.getRootElement();
// List list = root.getChildren();
List tzList = root.getChildren("tz");
// Element tz = root.getChild("tz");
// List tzList = tz.getChildren();
for(int i = 0 ; i < tzList.size() ; i++){
Element item = (Element)tzList.get(i);
// System.out.println(item.getName());
// System.out.println("item -->" + item.getChildText("tzid"));
Element tzidEle = item.getChild("tzid");
String tzid = tzidEle.getText();
System.out.println("tzid -->" + tzid);
Element tzbtEle = item.getChild("tzbt");
String tzbt = tzbtEle.getText();
System.out.println("tzbt -->" + tzbt);
Element tznrEle = item.getChild("tznr");
String tznr = tznrEle.getText();
System.out.println("tznr -->" + tznr);
Element ywtzbtEle = item.getChild("ywtzbt");
String ywtzbt = ywtzbtEle.getText();
System.out.println("ywtzbt -->" + ywtzbt);
Element ywtznrEle = item.getChild("ywtznr");
String ywtznr = ywtznrEle.getText();
System.out.println("ywtznr -->" + ywtznr);
}
System.out.println("\n=============================================================\n");
Element tzdx = root.getChild("tzdx");
List tzdxList = tzdx.getChildren("record");
for(int i = 0 ; i < tzdxList.size() ; i++){
Element item = (Element)tzdxList.get(i);
Element idEle = item.getChild("id");
String id = idEle.getText();
System.out.println("id -->" + id);
Element dhEle = item.getChild("dh");
String dh = dhEle.getText();
System.out.println("dh -->" + dh);
Element czEle = item.getChild("cz");
String cz = czEle.getText();
System.out.println("cz -->" + cz);
Element dxEle = item.getChild("dx");
String dx = dxEle.getText();
System.out.println("dx -->" + dx);
Element mailEle = item.getChild("mail");
String mail = mailEle.getText();
System.out.println("mail -->" + mail);
System.out.println("\n-------------------------------------------------------\n");
}
/*
* try{
SAXBuilder sb=new SAXBuilder();// 建立构造器
Document doc=sb.build(new FileInputStream(file));// 读入指定文件
Element root=doc.getRootElement();// 获得根结点
List list=root.getChildren();// 将根结点下的所有子节点放入List中
PreparedStatement pstmt=conn.prepareStatement("insert into t_entinfo(EntRegNo,EntName,LeRep,RegCap,RegDate,BuItem,Country,Province,Tel,Mobile_phone,Email,Address,Fax,HomePage,EntType,Group_ID) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
for(int i=0;i<list.size();i++){
System.out.println("/n-----------------------/n");
Element item=(Element)list.get(i);// 取得节点实例
Element EntRegNo=item.getChild("EntRegNo");// 取得当前节点的子节点
String entRegNo=EntRegNo.getText();// 取得当前节点的值
System.out.println("EntRegNo---->"+entRegNo);
Element EntName=item.getChild("EntName");// 取得当前节点的子节点
String entName=EntName.getText();// 取得当前节点的值
System.out.println("EntName---->"+entName);
Element LeRep=item.getChild("LeRep");// 取得当前节点的子节点
String leRep=LeRep.getText();// 取得当前节点的值
System.out.println("LeRep---->"+leRep);
Element RegCap=item.getChild("RegCap");// 取得当前节点的子节点
Double regCap=new Double(RegCap.getText()).doubleValue();// 取得当前节点的值
System.out.println("RegCap---->"+regCap);
Element RegDate=item.getChild("RegDate");// 取得当前节点的子节点
String regDate=RegDate.getText();// 取得当前节点的值
System.out.println("RegDate---->"+regDate);
Element BuItem=item.getChild("BuItem");// 取得当前节点的子节点
String buItem=BuItem.getText();// 取得当前节点的值
System.out.println("BuItem---->"+buItem);
Element Country=item.getChild("Country");// 取得当前节点的子节点
String country=Country.getText();// 取得当前节点的值
System.out.println("Country---->"+country); Element Province=item.getChild("Province");// 取得当前节点的子节点
String province=Province.getText();// 取得当前节点的值
System.out.println("Province---->"+province);
Element Tel=item.getChild("Tel");// 取得当前节点的子节点
String tel=Tel.getText();// 取得当前节点的值
System.out.println("Tel---->"+tel);
Element Mobile_phone=item.getChild("Mobile_phone");// 取得当前节点的子节点
String mobile_phone=Mobile_phone.getText();// 取得当前节点的值
System.out.println("Mobile_phone---->"+mobile_phone);
Element Email=item.getChild("Email");// 取得当前节点的子节点
String email=Email.getText();// 取得当前节点的值
System.out.println("Email---->"+email); Element Address=item.getChild("Address");// 取得当前节点的子节点
String address=Address.getText();// 取得当前节点的值
System.out.println("Address---->"+address);
Element Fax=item.getChild("Fax");// 取得当前节点的子节点
String fax=Fax.getText();// 取得当前节点的值
System.out.println("Fax---->"+fax);
Element HomePage=item.getChild("HomePage");// 取得当前节点的子节点
String homePage=HomePage.getText();// 取得当前节点的值
System.out.println("HomePage---->"+homePage);
Element EntType=item.getChild("EntType");// 取得当前节点的子节点
int entType=new Integer(EntType.getText()).intValue();// 取得当前节点的值
System.out.println("EntType---->"+entType);
Element Group_ID=item.getChild("Group_ID");// 取得当前节点的子节点
int group_ID=new Integer(Group_ID.getText()).intValue();// 取得当前节点的值
System.out.println("Group_ID---->"+group_ID);
if(conn!=null){
try{
pstmt.setString(1,entRegNo);
pstmt.setString(2,entName);
pstmt.setString(3,leRep);
pstmt.setDouble(4,regCap);
pstmt.setString(5,regDate);
pstmt.setString(6,buItem);
pstmt.setString(7,country);
pstmt.setString(8,province);
pstmt.setString(9,tel);
pstmt.setString(10,mobile_phone);
pstmt.setString(11,email);
pstmt.setString(12,address);
pstmt.setString(13,fax);
pstmt.setString(14,homePage);
pstmt.setInt(15,entType);
pstmt.setInt(16,group_ID);
pstmt.executeUpdate();
System.out.println("XML文件内容已存入数据库...");
}catch(SQLException e){
throw new SQLException("Cound not execute SQLquery."+e.toString());
}catch(Exception e){
throw new Exception("Cound not execute query.");
}
}
pstmt.close();
}
}catch(Exception e){
e.getMessage();
}*/
conn.close();
}
}
主要是针对XML的结构的。。
LZ看明白就OK。。
—————————————————————————————— /// 间隔符
/// </summary>
public string SpaceChar = " ";
/// <summary>
/// xsd构架文件名称
/// </summary>
public string XMLShemaFileName = "";
/// <summary>
/// 缩略图
/// </summary>
public System.Drawing.Image Overview;
/// <summary>
/// xml构架信息
/// </summary>
private XmlSchema schema;
/// <summary>
/// 必、选填参数 true的时候 显示选填的项 false的时候只显示必填项
/// </summary>
private bool isOptional = false;
/// <summary>
/// 历史值记录
/// </summary>
public System.Collections.Hashtable MetaValueTable = new System.Collections.Hashtable();
/// <summary>
/// 树的起始节点编号
/// </summary>
private int treeIndex = -1;
/// <summary>
/// 代码表
/// </summary>
private System.Collections.Hashtable CodeList = new System.Collections.Hashtable();
/// <summary>
/// 构造函数
/// </summary>
/// <param name="xsdfile">xsd文件地址</param>
public XmlShema2Tree(string xsdfile)
{
schema = new XmlSchema();
System.IO.FileInfo fileinfo = new FileInfo(xsdfile);
if (!fileinfo.Exists)
{
throw new Exception("元数据标准的XML Shema信息不存在:" + xsdfile);
}
XMLShemaFileName = fileinfo.Name;
StreamReader sw = new StreamReader(xsdfile, System.Text.Encoding.Default);
schema = XmlSchema.Read(sw, new ValidationEventHandler(SchemaValidationHandler));
sw.Close();
schema.Compile(new ValidationEventHandler(SchemaValidationHandler));
}
/// <summary>
/// 获取DTree生成树的脚本信息
/// </summary>
/// <param name="isOptional">必、选填参数</param>
/// <returns></returns>
public string GetDTreeScript(bool optional)
{
this.cbxlist = new System.Collections.Hashtable();
this.isOptional = optional;
this.treeIndex = -1;
this.JsScript = "";
StringBuilder str = new StringBuilder();
str.AppendLine("<script language=\"javascript\" src=\"javascript/dtree.js\" type=\"text/javascript\"></script>");
str.AppendLine("<link href=\"Common/Css/Default.css\" type=\"text/css\" rel=\"stylesheet\">");
str.AppendLine("<script language=\"javascript\" src=\"Common/JavaScript/DatePicker.js\" type=\"text/javascript\"></script>");
str.AppendLine("<script type=\"text/javascript\">");
str.AppendLine(" <!--");
str.AppendLine(" var categorytree = new dTree(\"categorytree\");");
//通过XSD Shema构件数的节点
DecodeSchema(schema, str, -1);
if (JsScript.Length > 0)
{
JsScript = JsScript.TrimEnd('|');
JsScript = JsScript.Replace(" ", "");
}
str.AppendLine(" document.write(categorytree);");
str.AppendLine(" var vctl = \"" + JsScript + "\";");
str.AppendLine(" function vv()");
str.AppendLine("{");
str.AppendLine(" if(vctl && vctl.length > 0)");
str.AppendLine(" {");
str.AppendLine(" var v = vctl.split('|');");
str.AppendLine(" var l = v.length;");
str.AppendLine(" for(var i=0;i<l;i++)");
str.AppendLine(" {");
str.AppendLine(" var tip = v[i];");
str.AppendLine(" i++;");
str.AppendLine(" var name = v[i];");
str.AppendLine(" var ctl = document.getElementById(name);");
str.AppendLine(" if(ctl && ctl.value =='')");
str.AppendLine(" {");
str.AppendLine(" alert('请填写 ' + tip);");
str.AppendLine(" ctl.focus();");
str.AppendLine(" return false;");
str.AppendLine(" }");
str.AppendLine(" }");
str.AppendLine(" }");
str.AppendLine("}");
str.AppendLine(" -->");
str.AppendLine("</script>"); string html = str.ToString();
foreach (string key in cbxlist.Keys)
{
string ckey = cbxlist[key].ToString();
System.Collections.ArrayList list = CodeList[ckey] as System.Collections.ArrayList;
string v = MetaValueTable.ContainsKey(key) ? MetaValueTable[key].ToString() : "";
string options = "";
foreach (string s in list)
{
if (s.Trim() != "")
{
if (v == s.Trim())
{
options += "<option value=\"" + s.Trim() + "\" selected>" + s.Trim() + "</option>";
}
else
{
options += "<option value=\"" + s.Trim() + "\">" + s.Trim() + "</option>";
}
}
}
html = html.Replace("{" + key + "}", options);
}
return html;
}
/// <summary>
/// 异常处理
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
private void SchemaValidationHandler(object sender, ValidationEventArgs args)
{
Console.WriteLine(args.Message);
} /// <summary>
/// 循环构件节点
/// </summary>
/// <param name="obj">XmlSchemaObject</param>
/// <param name="str">StringBuilder</param>
/// <param name="nodeindex">NodeIndex</param>
/// <returns></returns>
private int DecodeSchema(XmlSchemaObject obj, StringBuilder str, int nodeindex)
{
int newNodeIndex = nodeindex;
//所有类型
//XmlSchemaAnnotation annot = obj as XmlSchemaAnnotation;
//XmlSchemaAttribute attrib = obj as XmlSchemaAttribute;
//XmlSchemaFacet facet = obj as XmlSchemaFacet;
//XmlSchemaDocumentation doc = obj as XmlSchemaDocumentation;
//XmlSchemaAppInfo appInfo = obj as XmlSchemaAppInfo;
XmlSchemaElement element = obj as XmlSchemaElement;
XmlSchemaSimpleType simpleType = obj as XmlSchemaSimpleType;
XmlSchemaComplexType complexType = obj as XmlSchemaComplexType; if (element != null)
{
if (element.MinOccurs > 0 || (element.MinOccurs == 0 && isOptional))
{
XmlSchemaSimpleType st = element.SchemaType as XmlSchemaSimpleType;
XmlSchemaComplexType ct = element.SchemaType as XmlSchemaComplexType;
if (st != null || ct != null)
{
//simple || complex type element. Recurse.
CreateTreeNode_STCT(str, element, newNodeIndex, ref treeIndex);
DecodeSchema(element.SchemaType, str, treeIndex);
}
else
{
CreateTreeNode(str, element, newNodeIndex, ref treeIndex);
}
}
}
else if (simpleType != null)
{
XmlSchemaSimpleTypeRestriction rest = simpleType.Content as XmlSchemaSimpleTypeRestriction;
if (rest != null)
{
if (!CodeList.ContainsKey(simpleType.Name))
{
System.Collections.ArrayList list = new System.Collections.ArrayList();
foreach (XmlSchemaFacet schemaObject in rest.Facets)
{
list.Add(schemaObject.Value);
}
import java.io.IOException;import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;public class SAXPrinterTest extends DefaultHandler { public void startElement(String uri, String localName, String qName,
Attributes attr) throws SAXException {
System.out.print("<" + qName);
for (int i = 0; i < attr.getLength(); i++) {
System.out.print(" ");
System.out.print(attr.getQName(i));
System.out.print("=\"");
System.out.print(attr.getValue(i));
System.out.print("\"");
} System.out.print(">");
} public void characters(char[] ch, int start, int length)
throws SAXException {
System.out.print(new String(ch, start, length));
} public void endElement(String uri, String localName, String qName)
throws SAXException {
System.out.print("<" + qName + "/>");
} public static void main(String args[]) {
SAXParserFactory spf = SAXParserFactory.newInstance();
try {
SAXParser sp = spf.newSAXParser();
sp.parse(new File("****/***.xml"), new SAXPrinterTest());
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} }
}把****/***.xml改成你自己的路径试试!