Java 解析xml的方法:DOM,SAX

/*

 * Created on 2006-8-13

 *

 * TODO To change the template for this generated file go to

 * Window - Preferences - Java - Code Style - Code Templates

 */
package com.hotmail.scbit.SAX;

import java.util.*;



import org.xml.sax.*;

import org.xml.sax.helpers.DefaultHandler;



//解析类

public class DBContactsHandler extends DefaultHandler

{

	Contacts contact = null;

	

	private Stack tagsStack=new Stack();

    private Vector contacts = new Vector();

    

    private String id;

    private String name;

    private String project;

    private String telephone;

    private String email;

    private String msn;

    private String remark;

    

    public Vector getContacts()

    {

    	return this.contacts;

    }

    

    public void startElement(String uri,String localName,

                             String qName,Attributes attrs)

                      throws SAXException

    {

    	tagsStack.push(qName);

    }

    

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

    {



           

            String tag=(String)tagsStack.peek();

            

            if(tag.equals("id"))

            {

                this.id=new String(ch,start,length);

            }

            if(tag.equals("name"))

            {

                this.name=new String(ch,start,length);

            }

            if(tag.equals("project")){

            	this.project = new String(ch,start,length);

            }

            if(tag.equals("telephone"))

            {

                this.telephone=new String(ch,start,length);

            }

                

            if(tag.equals("email"))

            {

                this.email=new String(ch,start,length);

            }

            if(tag.equals("msn")){

            	this.msn=new String(ch,start,length);

            }

            if(tag.equals("remark")){

            	this.remark=new String(ch,start,length);

            }

    }

    

    public void endElement(String uri,String localName,String qName) throws SAXException

    {

            String tag=(String)tagsStack.pop();

            

            if(tag.equalsIgnoreCase("employe"))

            {

       

            	contact = new Contacts(

            			Integer.parseInt(this.id),

            			this.name,

            			this.project,

            			this.telephone,

            			this.email,

            			this.msn,

            			this.remark);

            	contacts.add(contact);

            	

            	System.out.println(this.id);

            	System.out.println(this.name);

            	System.out.println(this.project);

            	System.out.println(this.telephone);

            	System.out.println(this.email);

            	System.out.println(this.msn);

            	System.out.println(this.remark);

            }

    }

    

    public void endDocument() throws SAXException

    {

        System.out.println("查找完毕");

    }

}

//文档同上

// 将xml文档放在解析器里面进行解析



package com.hotmail.scbit.SAX;



import javax.xml.parsers.SAXParser;

import javax.xml.parsers.SAXParserFactory;

import java.io.File;

import java.util.Vector;



public class DBContactsParser 

{

	private final File file = new File("E://Java Object//contacts.xml");

	Vector contacts = new Vector();

	private void  parse()

	{

		try

		{

			DBContactsHandler handler = new DBContactsHandler();

			SAXParserFactory spFactory = SAXParserFactory.newInstance();

			SAXParser sp = spFactory.newSAXParser();

			sp.parse(file,handler);

			contacts = handler.getContacts();

		}

		

		catch(Exception e)

		{

			e.printStackTrace();

		}

	}

	

	public Vector getContactInfo()

	{

		this.parse();

		return this.contacts;

	}

	

}







package com.hotmail.scbit.DOM; import java.sql.*; import java.io.File; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import javax.xml.transform.TransformerFactory; import javax.xml.transform.Transformer; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.*; public class XMLDocumenrtBuilder { //根据结果集生成XML文档 public static void tableinput(ResultSet rs,File XMLFile) { try { ResultSetMetaData rsda = rs.getMetaData(); int count = rsda.getColumnCount(); // String ColumnName[] = new String[count]; // int ColumnType[] = new int[count]; // for(int i = 0;i < count; i ++) { ColumnName[i] = rsda.getColumnName(i+1); ColumnType[i] = rsda.getColumnType(i+1); System.out.println(ColumnName[i]); System.out.println(ColumnType[i]); } DocumentBuilderFactory doc = DocumentBuilderFactory.newInstance(); DocumentBuilder docbuilder = doc.newDocumentBuilder(); //新建一个文本对象 Document xmldoc = docbuilder.newDocument(); Element clomnElement = null; //字段名 Element rowElement = null;//子元素名 Text text = null;//字段值 //建立根元素 Element employesNode = xmldoc.createElement("employees"); while(rs.next()) { //建立子元素 rowElement = xmldoc.createElement("employe"); for(int i = 0;i < count ; i ++) { clomnElement = xmldoc.createElement(ColumnName[i]); if(ColumnType[i] == 4) { text = xmldoc.createTextNode(String.valueOf(rs.getInt(i + 1))); } if(ColumnType[i] == 12) { text = xmldoc.createTextNode(String.valueOf(rs.getString(i + 1))); } clomnElement.appendChild(text); rowElement.appendChild(clomnElement); } employesNode.appendChild(rowElement); } xmldoc.appendChild(employesNode); TransformerFactory tarnsFactory = TransformerFactory.newInstance(); Transformer tarnsformer = tarnsFactory.newTransformer(); DOMSource xmlDomSource = new DOMSource(xmldoc); StreamResult bookstarment = new StreamResult(XMLFile); tarnsformer.transform(xmlDomSource,bookstarment); System.out.println("tarnsformer createElement"); } catch(Exception e) { e.printStackTrace(); } } //解析XML文档,保存到数据库中 public static void tableoutput(Connection con,File XMLFile) { PreparedStatement pst = null; String Strsql = "insert into contacts values(?,?,?,?,?,?,?)"; int id = 0; String name = null; String project = null; String telephone = null; String email = null; String msn = null; String remark = null; try { pst = con.prepareStatement(Strsql); DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder(); Document doc = documentBuilder.parse(XMLFile); Element employeElement = doc.getDocumentElement(); NodeList employeNode = employeElement.getChildNodes(); for(int i = 0 ; i < employeNode.getLength();i = i + 1) { NodeList stuNodeList = employeNode.item(i).getChildNodes(); for(int j = 0;j < stuNodeList.getLength();j = j + 1) { Element col = (Element)stuNodeList.item(j); if(j == 0) { id = Integer.parseInt(col.getChildNodes().item(0).getNodeValue()); } if(j == 1) { name = col.getChildNodes().item(0).getNodeValue(); } if(j == 2) { project =col.getChildNodes().item(0).getNodeValue(); } if(j == 3) { telephone = col.getChildNodes().item(0).getNodeValue(); } if(j == 4){ email = col.getChildNodes().item(0).getNodeValue(); } if(j == 5){ msn = col.getChildNodes().item(0).getNodeValue(); } if(j == 6){ remark = col.getChildNodes().item(0).getNodeValue(); } } pst.setInt(1,id); pst.setString(2,name); pst.setString(3,project); pst.setString(4,telephone); pst.setString(5, email); pst.setString(6, msn); pst.setString(7, remark); pst.addBatch(); } pst.executeBatch(); System.out.println("数据库执行完毕"); } catch(Exception e) { e.printStackTrace(); System.out.println("bunengcharu:"); } } } //xml文档 <?xml version="1.0" encoding="UTF-8" standalone="no"?> <employees> <employe> <id>1</id> <name>babnsdf</name> <project>暂无</project> <telephone>153********</telephone> <email>gao@vip.sina.com</email> <MSN>jun@hotmail.com</MSN> <reach>暂无备注</reach> </employe> <employe> <id>2</id> <name>student</name> <project>标本库</project> <telephone>137********</telephone> <email>y@scbit.org</email> <MSN>wwx@hotmail.com</MSN> <reach>暂无备注</reach> </employe> <employe> <id>3</id> <name>zhanzhan</name> <project>HIS、LIS等综合查询</project> <telephone>131********</telephone> <email>tan@scbit.org</email> <MSN>mose@msn.com</MSN> <reach>暂无备注</reach> </employe> <employe> <id>4</id> <name>班拾红</name> <project>病源体鉴定</project> <telephone>133********</telephone> <email>ban@yahoo.com.cn</email> <MSN>ban@msn.com</MSN> <reach>暂无备注</reach> </employe> <employe> <id>5</id> <name>吴桂强</name> <project>暂无</project> <telephone>136********</telephone> <email>Vriu@hotmail.com</email> <MSN>Vriu@hotmail.com</MSN> <reach>暂无备注</reach> </employe> <employe> <id>6</id> <name>zhaowu</name> <project>分子分型</project> <telephone>137********</telephone> <email>jia@hotmail.com</email> <MSN>jia@hotmail.com</MSN> <reach>暂无备注</reach> </employe> <employe> <id>7</id> <name>lisi</name> <project>暂无</project> <telephone>158********</telephone> <email>liu@163.com</email> <MSN>chn@hotmail.com</MSN> <reach>暂无备注</reach> </employe> <employe> <id>8</id> <name>zhangsan</name> <project>暂无</project> <telephone>137********</telephone> <email>xian@gmail.com</email> <MSN>ange@hotmail.com</MSN> <reach>暂无备注</reach> </employe> <employe> <id>9</id> <name>baijuyi</name> <project>暂无</project> <telephone>137********</telephone> <email>a1a@163.com</email> <MSN>a1-@163.com</MSN> <reach>暂无备注</reach> </employe> <employe> <id>10</id> <name>wanganshi</name> <project>暂无</project> <telephone>137********</telephone> <email>dug@tom.com</email> <MSN>mes@hotmial.com</MSN> <reach>暂无备注</reach> </employe> <employe> <id>11</id> <name>ouyangxiu</name> <project>暂无</project> <telephone>138********</telephone> <email>chen@hotmail.com</email> <MSN>chen@hotmail.com</MSN> <reach>暂无备注</reach> </employe> <employe> <id>12</id> <name>dupu</name> <project>暂无</project> <telephone>135********</telephone> <email>xin@gmail.com</email> <MSN>yanyan@yahoo.com.cn</MSN> <reach>暂无备注</reach> </employe> <employe> <id>13</id> <name>libai</name> <project>暂无</project> <telephone>159********</telephone> <email>papa@hotmail.com</email> <MSN>papa@hotmail.com</MSN> <reach>暂无备注</reach> </employe> </employees>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值