Java用dom和sax解析xml代码(Jaxp)

使用的是解析开发包Jaxpsun官方),jdk中已经自带。

JAXP 开发包是J2SE的一部分,它由javax.xmlorg.w3c.dom org.xml.sax 包及其子包组成。在 javax.xml.parsers 包中,定义了几个工厂类,程序员调用这些工厂类,可以得到对xml文档进行解析的 DOM 或 SAX 的解析器对象。

Dom

Book.xml

<?xml version="1.0" encoding="UTF-8"?>
<书架>
	<书>
		<书名 name="dddd">java web就业</书名>
		<作者>张孝祥</作者>
		<售价>40</售价>	
	</书>
	<书>
		<书名>C++教程</书名>
		<作者>自己</作者>
		<售价>50</售价>	
	</书>
</书架>

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

//使用dom方式对xml文档进行CRUD
public class Demo3 {
	//读取<书名>C++教程</书名>
	@Test
	public void read1() throws Exception
	{
		 DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
		 DocumentBuilder builder=factory.newDocumentBuilder();
		 Document document=builder.parse("src/book.xml");
		 NodeList list=document.getElementsByTagName("书名");
		 Node node=list.item(1);
		 String content=node.getTextContent();
		 System.out.println(content);//C++教程
	}
	//得到文档中所有标签
	@Test
	public void read2() throws Exception
	{
		 DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
		 DocumentBuilder builder=factory.newDocumentBuilder();
		 Document document=builder.parse("src/book.xml");
		 NodeList list=document.getElementsByTagName("书名");
		 Node root=document.getElementsByTagName("书架").item(0);
		 list(root);		 
	}

	private void list(Node node) {
		Node child;
		if (node instanceof Element)
			System.out.println(node.getNodeName());
		NodeList nodelist=node.getChildNodes();
		for (int i=0;i<nodelist.getLength();i++)
		{	
			child=nodelist.item(i);
			list(child);
		}		
	}
	//得到文档中标签属性<书名 name="xxxx">java web就业</书名>
	@Test
	public void read3() throws Exception
	{
		 DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
		 DocumentBuilder builder=factory.newDocumentBuilder();
		 Document document=builder.parse("src/book.xml");

		 
		 NodeList list=document.getElementsByTagName("书名");
		 Node node=list.item(0);
		 if(node.hasAttributes()){
			 NamedNodeMap nodemap=node.getAttributes();
			 for(int i=0;i<nodemap.getLength();i++)
			 {
				 Node nd=nodemap.item(i);
				 String strname=nd.getNodeName();
				 String strval=nd.getNodeValue();
				 System.out.println(strname+":"+strval);//name:dddd
				 
			 }			 
		 }
		 
		 Element node2=(Element)list.item(0);
		 String str3=node2.getAttribute("name");
		 System.out.println("__"+str3);//__dddd
	}
	//<售价>10</售价>	
	@Test
	public void add() throws Exception{
		 DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
		 DocumentBuilder builder=factory.newDocumentBuilder();
		 Document document=builder.parse("src/book.xml");
		 //创建节点
		 Element price=document.createElement("售价");
		 price.setTextContent("59.0元");
		 //把创建的节点放到第一本书上
		 document.getElementsByTagName("书").item(0).appendChild(price);
		 //把跟新后的内容写回文档
		 Transformer transformer=TransformerFactory.newInstance().newTransformer();
		 DOMSource source=new DOMSource(document);
		 FileOutputStream outstream =new FileOutputStream(new File("src/outbook.xml"));
		 StreamResult reslut=new StreamResult(outstream);
		 transformer.transform(source, reslut);
		 outstream.close();		
	}
	
	//向文档中指定位置上添加节点  <售价>10</售价>	
	@Test
	public void add2() throws Exception{
		 DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
		 DocumentBuilder builder=factory.newDocumentBuilder();
		 Document document=builder.parse("src/book.xml");
		 //创建节点
		 Element price=document.createElement("售价");
		 price.setTextContent("59.0元");
		 //得到参考节点
		 Element refNode=(Element)document.getElementsByTagName("售价").item(0);
		 //得到挂崽的节点
		 Element book=(Element)document.getElementsByTagName("书").item(0);
		 //把创建的节点放到第一本书上
		 document.getElementsByTagName("书").item(0).appendChild(price);
		 // 往book节点指定位置插值
		 book.insertBefore(price, refNode);
		 Transformer transformer=TransformerFactory.newInstance().newTransformer();
		 DOMSource source=new DOMSource(document);
		 FileOutputStream outstream =new FileOutputStream(new File("src/outbook2.xml"));
		 StreamResult reslut=new StreamResult(outstream);
		 transformer.transform(source, reslut);
		 outstream.close();		
	}
	//向文档节点 添加属性 <售价>10</售价>	
	@Test
	public void addAtt() throws Exception{
		 DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
		 DocumentBuilder builder=factory.newDocumentBuilder();
		 Document document=builder.parse("src/book.xml");
		 
		 //得到参考节点
		 Element refNode=(Element)document.getElementsByTagName("售价").item(0);
		 refNode.setAttribute("addAtrr","new cha ru value");
		 
		
		
		 Transformer transformer=TransformerFactory.newInstance().newTransformer();
		 DOMSource source=new DOMSource(document);
		 FileOutputStream outstream =new FileOutputStream(new File("src/outbook3.xml"));
		 StreamResult reslut=new StreamResult(outstream);
		 transformer.transform(source, reslut);
		 outstream.close();		
	}
	//删除 <售价>10</售价>	
	@Test
	public void delete() throws Exception{
		 DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
		 DocumentBuilder builder=factory.newDocumentBuilder();
		 Document document=builder.parse("src/book.xml");
		 
		 //得到要删除的节点
		 Element refNode=(Element)document.getElementsByTagName("售价").item(0);
		 refNode.getParentNode().removeChild(refNode);
		
		
		 Transformer transformer=TransformerFactory.newInstance().newTransformer();
		 DOMSource source=new DOMSource(document);
		 FileOutputStream outstream =new FileOutputStream(new File("src/outbook3.xml"));
		 StreamResult reslut=new StreamResult(outstream);
		 transformer.transform(source, reslut);
		 outstream.close();		
	}
	//更新 售价
	@Test
	public void update() throws Exception{
		 DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
		 DocumentBuilder builder=factory.newDocumentBuilder();
		 Document document=builder.parse("src/book.xml");
		 
		 //得到要更新的节点
		 Element refNode=(Element)document.getElementsByTagName("售价").item(0);
		 refNode.setTextContent("1000");
		 
		 Transformer transformer=TransformerFactory.newInstance().newTransformer();
		 DOMSource source=new DOMSource(document);
		 FileOutputStream outstream =new FileOutputStream(new File("src/outbook3.xml"));
		 StreamResult reslut=new StreamResult(outstream);
		 transformer.transform(source, reslut);
		 outstream.close();	
		 
	}

}


SAX:

<?xml version="1.0" encoding="gb2312"?>

<书架> 
  <书> 
    <书名 name="dddd">java web就业</书名>  
    <作者>张孝祥</作者>  
    <售价>309元</售价>
    <售价>309元</售价>  
    <售价>40</售价>  
    <售价>111</售价>  
    <售价>111</售价>  
    <售价>111</售价>  
    <售价>111</售价> 
  </书>  
  <书> 
    <书名 name="xxxx">C++教程</书名>  
    <作者>张三</作者>  
    <售价>50</售价> 
  </书> 
</书架>


方法一:得到xml文档所有内容

package cn.itcast.sax;

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.ContentHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

public class Demo1 {

	/**
	 * sax解析xml文档
	 * @throws SAXException 
	 * @throws ParserConfigurationException 
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		//1.创建解析工厂
		SAXParserFactory factory=SAXParserFactory.newInstance();
		//2.得到解析器
		SAXParser sp=factory.newSAXParser();
		//3.得到读取器
		XMLReader reader=sp.getXMLReader();
		//4.设置内容处理器
		reader.setContentHandler(new ListHandler());
		//5.读取xml文档内容
		reader.parse("src/book.xml");
	}
}
//得到xml文档所有内容
class ListHandler implements ContentHandler{

	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		System.out.println(new String(ch,start,length));		
	}

	@Override
	public void endDocument() throws SAXException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		System.out.println("</"+qName+">");
		
	}

	@Override
	public void endPrefixMapping(String prefix) throws SAXException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void ignorableWhitespace(char[] ch, int start, int length)
			throws SAXException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void processingInstruction(String target, String data)
			throws SAXException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void setDocumentLocator(Locator locator) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void skippedEntity(String name) throws SAXException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void startDocument() throws SAXException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes atts) throws SAXException {
		System.out.println("<"+qName+">");	
		for (int i=0;atts!=null && i<atts.getLength();i++){
			String attName=atts.getQName(i);
			String attValue=atts.getValue(i);
			System.out.println(attName+"="+attValue);
		}
	}

	@Override
	public void startPrefixMapping(String prefix, String uri)
			throws SAXException {
		// TODO Auto-generated method stub
		
	}
	
}

方法二:获取指定标签  

package cn.itcast.sax;

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.ContentHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

public class Demo2 {

	/**
	 * sax解析xml文档
	 * @throws SAXException 
	 * @throws ParserConfigurationException 
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		//1.创建解析工厂
		SAXParserFactory factory=SAXParserFactory.newInstance();
		//2.得到解析器
		SAXParser sp=factory.newSAXParser();
		//3.得到读取器
		XMLReader reader=sp.getXMLReader();
		//4.设置内容处理器
		reader.setContentHandler(new TagValueHandler());
		//5.读取xml文档内容
		reader.parse("src/book.xml");
	}
}
//获取指定标签  作者 的值
class TagValueHandler extends DefaultHandler{
	private String currentTag;//记住当前解析器得到的是什么标签
	private int needNumber=2;//记住想获取第几个作者标签的值
	private int currentNumber;//当前解析的是第几个	
	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		currentTag=qName;
		if("作者".equals(currentTag))
			currentNumber++;
	}
	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		if("作者".equals(currentTag)&& currentNumber==needNumber){
			System.out.println(new String(ch,start,length));
		}
	}
	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		currentTag=null;
	}


	
}

方法三:用javabean封装xml

package cn.itcast.sax;

public class Book {
	private String name;
	private String author;
	private String price;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAuthor() {
		return author;
	}
	public void setAuthor(String author) {
		this.author = author;
	}
	public String getPrice() {
		return price;
	}
	public void setPrice(String price) {
		this.price = price;
	}
}

package cn.itcast.sax;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

public class Demo3 {

	/**
	 * sax解析xml文档
	 */
	public static void main(String[] args) throws Exception {
		//1.创建解析工厂
		SAXParserFactory factory=SAXParserFactory.newInstance();
		//2.得到解析器
		SAXParser sp=factory.newSAXParser();
		//3.得到读取器
		XMLReader reader=sp.getXMLReader();
		//4.设置内容处理器
		BeanListHandler handle=new BeanListHandler();
		reader.setContentHandler(handle);
		//5.读取xml文档内容
		reader.parse("src/book.xml");
		

		List<Book> list=handle.getList();
		list.iterator();
		
	}
}
//把每一本书封装到一个book对象,并把book对象
class BeanListHandler extends DefaultHandler{
	private List<Book> list=new ArrayList<Book>();
	public List<Book> getList() {
		return list;
	}

	private String currentTag;
	private Book book;
	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		currentTag=qName;
		if("书".equals(currentTag)){
			book=new Book();
		}
	}
	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		if("书名".equals(currentTag)){
			book.setName(new String(ch,start,length));
		}
		if("作者".equals(currentTag)){
			book.setAuthor(new String(ch,start,length));
		}
		if("售价".equals(currentTag)){
			book.setPrice(new String(ch,start,length));
		}
	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		if(qName.equals("书")){
			list.add(book);
			book=null;
		}
		currentTag=null;//这句有必要
	}	
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值