xml解析

    xml解析
        1.介绍解析方式
        2.dom解析
        3.sax解析
        4.dom4j(重点)
        5.xpath
        6.示例---xml解析练习
    ==========================================
    xml解析      
        什么是xml解析?
            就是对xml文件中的内容可以通过提供的API进行读写操作。
            
        xml它的解析方式有几种?
            1.dom解析
            2.sax解析
            
        dom解析是官方给的标准的xml解析方式
        sax解析不早官方.
        
        dom解析是什么?
            是将整个xml文件形成一个dom树,加载到内在中。它可以对文档进行读写操作。
            缺点:文档比较大,它的效率比较低,有可能引起内存溢出。
        sax解析
            它只可以读操作。
            sax解析它是一种基于事件驱动方式,只能读。并且是一行一行读取。
            缺点:它不可以进行写操作.
            
        xml解析API
            1.jaxp---它是sun官方提供的一套dom,sax 解析的API.
            2.jdom
            3.dom4j----在实际操作中应用比较多.
            4.xstream
            
        jaxp----dom解析:
            jaxp 在使用时,不需要导入其它包,只需要有jdk就可以,因为它是javase的一部分.
            
            文档树中的节点关系:
                所有节点都是Node
                Node分成 1.Element(元素)   2.Attribute(忏悔)   3.Text(文本)
                
                Document代表整个文档,它也是Node.
                
            dom    操作步骤
                // 1.得到解析器工厂
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                // 2.通过工厂得到解析器
                DocumentBuilder builder = factory.newDocumentBuilder();

                // 3.通过解析器得到文档对象Document
                File file = new File("xml/books.xml");
                Document document = builder.parse(file);
                
        ================================================================    
        dom回写
            public static void domToFile(Document document, File file)
                throws TransformerException {
            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer tf = factory.newTransformer();
            tf.transform(new DOMSource(document), new StreamResult(file));
        }
            
    =================================================================================
    sax解析-----只能读取
        它是基于事件驱动
        
        sax解析步骤
            // // 1.得到sax解析工厂
            // SAXParserFactory factory = SAXParserFactory.newInstance();
            //
            // // 2.通过工厂获取解析器
            // SAXParser parse = factory.newSAXParser();
            //
            // // 3.通过解析器获取一个读取器
            // XMLReader reader = parse.getXMLReader();
            //
            // // 4.给读取器注册监听,当读取器读取操作时,我们可以监听到.
            // reader.setContentHandler(new MyContentHander());
            //
            // // 5.通过读取器解析xml文件
            // reader.parse("xml/books.xml");
            
            

            // 以上五步操作可以写成三步
            // 1.得到sax解析工厂
            SAXParserFactory factory = SAXParserFactory.newInstance();

            // 2.通过工厂获取解析器
            SAXParser parse = factory.newSAXParser();

            // 3.直接验parse添加监听
            parse.parse(new File("xml/books.xml"), new MyContentHander());
            
===================================================================================================================
        dom4j解析
            dom4j要想使用,必须导包.
            
            dom4j使用步骤
                1.导入jar包  dom4j-1.6.1.jar
                
                怎样导入jar包
                    1.java project    在工程下创建一个目录lib  将jar包复制到lib下  build path 变成奶瓶效果。
                    2.web project   在WebRoot下WEB-INF下找到lib目录,直接复制就ok.
                    
                    
                2.操作。    
                    2.1 得到SaxReader对象
                        SaxReader reader=new SaxReader();
                        
                        Document document=reader.read(File file);
                        
                        Element root=document.getRootElement();
                        
                    2.2 Element下有
                        1.elements()  得到所有子元素,返回的是List<Element>
                        2.element(String name); 获取其下指定名称的子元素.
                        
                        getText();获取标签中的文本信息.
                        
            ===================================================
            将books.xml下所有price值打印到控制台?    
            
            
            
            1.查询操作
                1.1 查询属性
                    Attribute    Element.attribute(String name);                    
                    Attribute.getValue();                    
                    与下面这一句一样.
                    String Element.attributeValue(String name);
                    
                1.2查询子元素内容
                    Element.element(String name).getText();
                    与下面这一句一样
                    Element.elementText(String name);
            
            2.修改操作
                2.1 修改属性
                    Element.addAttribute(String name,String value)
                2.2 修改文本
                    setText();
                    
                2.3回写操作
                    XMLWriter writer=new XMLWriter(new FileWriter(File file));
                    
                    writer.write(Document);
                    
                ===================================================
                乱码出现的原因:
                    xml文件本身编码是utf-8
                    XMLWriter writer = new XMLWriter(new FileWriter(file));
                    这句话向xml文件中写入,使用的是FileWriter,它本身采用的系统编码GBk.
                    
                解决方案:
                    XMLWriter writer = new XMLWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
                    通过指定流的编码来解决。
                    
                    dom4j中提供了解决的方案:
                        OutputFormat 这个类可以指定编码与指定格式化.
                        
                    new XMLWriter(OutputStream os,OutputFormat of);    
                    
                    OutputFormat format=OutputFormat.createCompactFormat(); //得到一个OutputFormat对象  不对xml文件进行格式化
                    OutputFormat format=OutputFormat.createPrettyPrint(); //可以对xml文件进行格式化
                    format.setEncoding("utf-8"); //指定编码
                    
            3.添加操作
                1.创建元素
                    在dom4j中要想创建元素使用DocumentHelper类来完成
                    Element e=DocumentHelper.createElement(String name);
                
                2.添加元素
                    Element.add();
            
            4.删除操作
                1.删除属性
                    Element.remove(Attribute a);
                    book.remove(book.attribute("type"));

                2.删除子元素.
                    父元素.remove(子元素);
                    
                    得到父元素   getParent();
                    
                    也可以通过List集合进行操作
                    List<Element> es = book.elements();
                    es.remove(es.size() - 1);
    ====================================================
    XPATH:
        XPath 是一门在 XML 文档中查找信息的语言
        
        dom4j支持xpath语法.
        使用:
            1.必须导入一个xpath支持的jar包  jaxen-1.1-beta-6.jar
            2.xpath只用于查找.
                而dom4j中一般情况只使用两个方法来完成查找操作.
                
                List getSelectNodes(String xpath);
                Node selectSingleNode(String xpath);
        
        
    ===================================================================================    
    xml解析案例
        商品信息管理
            其实就是CRUD操作。
        商品信息
            编号(id)、名称(name)、售价(price)、数量(number)、描述(description)
            
        包结构:
            cn.itcast.product.view;  用于视图类  作用是用于接收数据
            cn.itcast.product.ctrl;  控制层,它用于view与operation之间的过渡
            cn.itcast.product.operation; 操作层,它用于真正与xml文件进行读写操作.
            cn.itcast.product.utils; 工具类  Dom4jUtils
            cn.itcast.product.domain; 用于装实体类  Product类
            
        完成添加操作:
            
        
package cn.itcast.dom4j;

import java.io.File;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

//遍历操作---了解
public class Dom4jDemo1 {

	public static void main(String[] args) throws DocumentException {

		// 1.创建SaxReader

		SAXReader reader = new SAXReader();

		// 2.通过reader获取Document
		Document document = reader.read(new File("xml/books.xml"));

		// 3.得到根元素
		Element root = document.getRootElement();

		// elements element(String name)
		// List<Element> es = root.elements();

		// 问题:不知道子元素下是否还有子元素.-----递归

		// boolean flag=root.hasContent() 可以通过这个方法判断

		// if(es.size()>0) 通过长度来判断.

		findChild(root);

	}

	public static void findChild(Element e) {
		List<Element> children = e.elements();

		if (children.size() > 0) {
			for (Element el : children) {
				findChild(el);
			}
		}else{
			System.out.println(e.getName()+":"+e.getText());
		}
	}
}

Dom4jDemo2.java

package cn.itcast.dom4j;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.XMLWriter;
import org.junit.Test;

import cn.itcast.utils.Dom4jUtils;

//使用dom4j对xml文件进行crud操作.
public class Dom4jDemo2 {

	// 1.查找 要求:得到第一个book的type属性 得到第一个book下的price子元素的内容.
	public void read() throws DocumentException {
		// 1.得到document对象
		Document document = Dom4jUtils.getDocument(new File("xml/books.xml"));

		// 2.得到根元素
		Element root = document.getRootElement();

		// 3.得到第一个book元素
		// Element book=(Element) root.elements().get(0);
		Element book = root.element("book"); // 如果root下有多个book子元素,只获取的是第一个

		// 4.得到属性type
		// Attribute type = book.attribute("type"); //根据名称获得属性对象
		// String typevalue = type.getValue(); //根据属性获取值.
		// System.out.println(typevalue);
		String typevalue = book.attributeValue("type"); // 直接获取属性值
		System.out.println(typevalue);

		// 5.得到price子元素内容
		// String text=book.element("price").getText();
		// System.out.println(text);
		String text = book.elementText("price");
		System.out.println(text);

	}

	// 2.修改操作 update
	// 将第一个book中的name的值修改为itcast
	// 将第一个book的属性type修改为zh
	@Test
	public void update() throws DocumentException, IOException {
		File file = new File("xml/books.xml");
		// 1.得到document对象
		Document document = Dom4jUtils.getDocument(file);

		// 2.得到根元素
		Element root = document.getRootElement();

		// 3.得到name元素.
		Element book = root.element("book");
		Element name = book.element("name");

		// 4.修改name元素中的文本

		name.setText("java编程思想");
		// 修改属性
		book.addAttribute("type", "中文");

		// 5.回写
		// XMLWriter writer = new XMLWriter(new FileWriter(file));
		// //FileWriter它所使用的编码默认是系统编码.而我们系统编码是GBK
		XMLWriter writer = new XMLWriter(new OutputStreamWriter(
				new FileOutputStream(file), "UTF-8"));
		writer.write(document);
		writer.flush();
		writer.close();

	}

	@Test
	public void update1() throws DocumentException, IOException {
		File file = new File("xml/books.xml");
		// 1.得到document对象
		Document document = Dom4jUtils.getDocument(file);

		// 2.得到根元素
		Element root = document.getRootElement();

		// 3.得到name元素.
		Element book = root.element("book");
		Element name = book.element("name");

		// 4.修改name元素中的文本

		name.setText("java编程思想");
		// 修改属性
		book.addAttribute("type", "中文");

		// 5.回写
		// OutputFormat format=OutputFormat.createCompactFormat();
		// //得到一个OutputFormat对象 不对xml文件进行格式化
		// OutputFormat format=OutputFormat.createPrettyPrint(); //可以对xml文件进行格式化
		// format.setEncoding("utf-8"); //指定编码
		// XMLWriter writer = new XMLWriter(new FileOutputStream(file), format);
		// writer.write(document);
		// writer.flush();
		// writer.close();

		Dom4jUtils.domToFile(document, file);

	}

	// 3.添加操作 create
	// 要求: 在第一个book上添加type属性 在第一个book下添加一个子元素<type></type>
	@Test
	public void create1() throws DocumentException, IOException {
		File file = new File("xml/books.xml");
		// 1.得到document对象
		Document document = Dom4jUtils.getDocument(file);

		// 2.得到根元素
		Element root = document.getRootElement();

		// 3.添加属性type
		Element book = root.element("book");

		book.addAttribute("type", "en");

		// 4.添加子元素
		// 4.1创建子元素
		Element type = DocumentHelper.createElement("type");
		// 4.2对子元素进入操作.
		type.setText("中文");
		// 4.3将子元素添加到父元素中.
		book.add(type);
		// 回写

		Dom4jUtils.domToFile(document, file);
	}

	// 添加操作
	// 要求:在books下添加
	// <book>
	// <name>thinking in python</name>
	// <price>49</price>
	// <author>fox</author>
	// </book>
	@Test
	public void create2() throws DocumentException, IOException {
		File file = new File("xml/books.xml");
		// 1.得到document对象
		Document document = Dom4jUtils.getDocument(file);

		// 2.得到根元素
		Element root = document.getRootElement();

		// 3.创建子元素.
		Element book = DocumentHelper.createElement("book");
		Element name = DocumentHelper.createElement("name");
		name.setText("thinking in python");
		Element price = DocumentHelper.createElement("price");
		price.setText("49");
		Element author = DocumentHelper.createElement("author");
		author.setText("fox");

		book.add(name);
		book.add(price);
		book.add(author);
		root.add(book);

		// 回写
		Dom4jUtils.domToFile(document, file);
	}

	// 添加-----String与Document的转换.
	@Test
	public void create3() throws DocumentException, IOException {
		File file = new File("xml/books.xml");
		// 1.得到document对象
		Document document = Dom4jUtils.getDocument(file);

		// 2.得到根元素
		Element root = document.getRootElement();

		// 3.
		String msg = " <book><name>thinking in python</name><price>49</price><author>fox</author></book>";
		Document doc = DocumentHelper.parseText(msg); // 将字符串转换成Document
		root.add(doc.getRootElement());

		// 回写
		Dom4jUtils.domToFile(document, file);
	}

	// 4.删除操作
	// 要求:将第一个book的属性type删除 将book的type元素删除.
	@Test
	public void delete() throws DocumentException, IOException {
		File file = new File("xml/books.xml");
		// 1.得到document对象
		Document document = Dom4jUtils.getDocument(file);

		// 2.得到根元素
		Element root = document.getRootElement();

		// 3.删除.
		// 3.1删除属性
		Element book = root.element("book");
		book.remove(book.attribute("type"));

		// 3.2删除子元素.
		// book.remove(book.element("type"));
		// Element type = book.element("type"); // 得到book下的type元素.

		// type.getParent().remove(type);
		List<Element> es = book.elements();
		es.remove(es.size() - 1);

		// 回写
		Dom4jUtils.domToFile(document, file);
	}
}
Dom4jDemo3.java

package cn.itcast.dom4j;

import java.io.File;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;

import cn.itcast.utils.Dom4jUtils;

//xpath应用
public class Dom4jDemo3 {

	public static void main(String[] args) throws DocumentException {
		// 1.得到document对象
		Document document = Dom4jUtils.getDocument(new File("xml/books.xml"));

		// List<Element> names=document.selectNodes("//name");
		// //获取xpath语法指定的元素,返回的是一个List集合
		//
		// for(Element name:names){
		// System.out.println(name.getText());
		// }
		//
		// Element name = (Element) document.selectSingleNode("//name");//
		// 获取xpath语法指定的元素,返回的是一个Element
		//
		// System.out.println(name.getText());
		
		//将name元素中属性id值为2这个元素的文本信息得到。
		Element name = (Element) document.selectSingleNode("//name[@id='2']");
		
		System.out.println(name.getText());
		
	}
}
Dom4jUtils.java
package cn.itcast.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class Dom4jUtils {

	// 获取Document
	public static Document getDocument(File file) throws DocumentException {
		// 1.创建SaxReader

		SAXReader reader = new SAXReader();

		// 2.通过reader获取Document
		Document document = reader.read(file);
		return document;
	}

	// 回写操作
	public static void domToFile(Document document, File file)
			throws IOException {
		OutputFormat format = OutputFormat.createPrettyPrint(); // 可以对xml文件进行格式化
		format.setEncoding("utf-8"); // 指定编码
		XMLWriter writer = new XMLWriter(new FileOutputStream(file), format);
		writer.write(document);
		writer.flush();
		writer.close();
	}
}

上午

DomDemo1

package cn.itcast.dom;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
//dom操作基本
public class DomDemo1 {

	public static void main(String[] args) throws Exception {
		// 1.得到解析器工厂
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		// 2.通过工厂得到解析器
		DocumentBuilder builder = factory.newDocumentBuilder();

		// 3.通过解析器得到文档对象Document
		File file = new File("xml/books.xml");
		Document document = builder.parse(file);

		// 使用document来操作xml文档---读取.

		// 获取thinking in java
		NodeList list = document.getElementsByTagName("name"); // 获取标签名称叫name的所有标签.

		// NodeList中有两个方法 item(int index) getLength

		// System.out.println(list.getLength());

		for (int i = 0; i < list.getLength(); i++) {
			Node name = list.item(i);

			// 得到节点中的文本信息.
			String msg = name.getTextContent();

			System.out.println(msg);
		}
	}
}

demo2

package cn.itcast.dom;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

//dom解析中常用三个方法
public class DomDemo2 {

	public static void main(String[] args) throws ParserConfigurationException,
			SAXException, IOException {
		// 1.得到解析器工厂
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		// 2.通过工厂得到解析器
		DocumentBuilder builder = factory.newDocumentBuilder();

		// 3.通过解析器得到文档对象Document
		File file = new File("xml/books.xml");
		Document document = builder.parse(file);

		// 获取books节点.
		NodeList list = document.getElementsByTagName("books");

		Node books = list.item(0);

		// 获取books下所有子元素.
		NodeList childs = books.getChildNodes();

		System.out.println(childs.getLength()); //5 因为xml文件中的所有空白字符也是Node
		
		//需要判断节点类型. getNodeName  getNodeType  getNodeValue三个方法.
		
		//对books下所有子元素进行遍历
		for(int i=0;i<childs.getLength();i++){
			
			Node node=childs.item(i);
			
			//判断node它是Element
			
			if(node.getNodeType()==Node.ELEMENT_NODE){
				
				NodeList booklist=node.getChildNodes(); //得到book下所有子元素
				
				System.out.println(booklist.getLength());
				
				
				return;
			}
			
			
			//System.out.println(node.getNodeName()+"---"+node.getNodeType()+"---"+node.getNodeValue());
			
			//book---1---null
			//System.out.println("==================================");
		  }

	}
}

demo3

package cn.itcast.dom;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import cn.itcast.utils.DomUtils;

//回写操作--修改操作
public class DomDemo3 {

	public static void main(String[] args) throws Exception {
		File file = new File("xml/books.xml");
		// 获取document对象.
		Document document = DomUtils.getDocument(file);

		// 需求:将第二个book中的name的文本修改成 "C++编程思想"
		// 1.得到第二个book的name标签.
		NodeList list = document.getElementsByTagName("name");
		Node name = list.item(1);

		// 2.修改
		name.setTextContent("C++编程思想");

		// 回写操作.
		DomUtils.domToFile(document, file);
	}
}

demo4

package cn.itcast.dom;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

import cn.itcast.utils.DomUtils;

//添加操作--在第一个book上添加一个属性  type="en" 在第一个book中添加一个子元素 <type>编程</type>
public class DomDemo4 {
	public static void main(String[] args) throws ParserConfigurationException,
			SAXException, IOException, TransformerException {
		// 1.得到document对象
		File file = new File("xml/books.xml");
		Document document = DomUtils.getDocument(file);
		// 2.查找到第一个book元素

		Element book = (Element) document.getElementsByTagName("book").item(0);

		// 3.在book元素上添加属性 添加子元素.
		//3.1添加属性
		book.setAttribute("type", "en");
		//3.2添加子元素
		Element type=document.createElement("type"); //创建元素
		type.setTextContent("编程");
		book.appendChild(type);
		// 4.回写
		DomUtils.domToFile(document, file);
	}
}
Dom4jDemo1
package cn.itcast.dom4j;

import java.util.List;
import java.io.File;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

//快速入门
public class Dom4jDemo1 {

    public static void main(String[] args) throws DocumentException {
        // 1.创建SaxReader

        SAXReader reader = new SAXReader();
        File file = new File("xml/books.xml");

        // 2.获取一个Document对象.
        Document document = reader.read(file);

        // 3.得到根元素
        Element root = document.getRootElement(); // 相当于得到books标签.

        List<Element> es = root.elements(); // 得到所有子元素

        for (Element e : es) {
            Element name = e.element("name"); // e相当于是book元素 得到了book下的name元素

            System.out.println(name.getText()); //得到name中的文本信息
        }
    }
}
MyFrame。java

package cn.itcast.sax;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;

//监听器
public class MyFrame extends JFrame implements ActionListener {
	JButton btn = new JButton("点我试试"); // 事件源 它可以产生ActionEvent事件
										// ActionEvent事件的监听器叫ActionListener

	public MyFrame() {

		// 需要对事件源进行注册监听
		//btn.addActionListener(this);

		this.add(btn);
		this.setDefaultCloseOperation(3);
		this.setBounds(100, 100, 300, 300);
		this.setVisible(true);
	}

	public static void main(String[] args) {
		new MyFrame();
	}

	@Override
	public void actionPerformed(ActionEvent e) {

		System.out.println("hello.....");
	}

}
SaxDemo.java
package cn.itcast.sax;

import java.io.File;
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.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

//使用sax解析方式对books.xml文件进行读取操作
public class SaxDemo {
	public static void main(String[] args) throws ParserConfigurationException,
			SAXException, IOException {

		// // 1.得到sax解析工厂
		// SAXParserFactory factory = SAXParserFactory.newInstance();
		//
		// // 2.通过工厂获取解析器
		// SAXParser parse = factory.newSAXParser();
		//
		// // 3.通过解析器获取一个读取器
		// XMLReader reader = parse.getXMLReader();
		//
		// // 4.给读取器注册监听,当读取器读取操作时,我们可以监听到.
		// reader.setContentHandler(new MyContentHander());
		//
		// // 5.通过读取器解析xml文件
		// reader.parse("xml/books.xml");
		
		

		// 以上五步操作可以写成三步
		// 1.得到sax解析工厂
		SAXParserFactory factory = SAXParserFactory.newInstance();

		// 2.通过工厂获取解析器
		SAXParser parse = factory.newSAXParser();

		// 3.直接验parse添加监听
		parse.parse(new File("xml/books.xml"), new MyContentHander());
	}
}

class MyContentHander extends DefaultHandler {

	@Override
	public void startDocument() throws SAXException {
		System.out.println("开始读取文档");
	}

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes atts) throws SAXException {
		String values = "";
		for (int i = 0; i < atts.getLength(); i++) { // 得到所有的忏悔
			String value = atts.getValue(i); // 获取第i个属性值
			String name = atts.getQName(i); // 获取第i个属性名称
			values += " " + name + "=\"" + value + "\"";
		}
		if (values != null) {
			System.out.println("<" + qName + values + ">");
		} else {
			System.out.println("<" + qName + ">");
		}
	}

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

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

	@Override
	public void endDocument() throws SAXException {
		System.out.println("结束读取文档");
	}

}
DomUtils.java
package cn.itcast.utils;

import java.io.File;
import java.io.IOException;

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

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

public class DomUtils {
	// 获取Document对象
	public static Document getDocument(File file)
			throws ParserConfigurationException, SAXException, IOException {
		// 1.得到解析器工厂
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		// 2.通过工厂得到解析器
		DocumentBuilder builder = factory.newDocumentBuilder();

		// 3.通过解析器得到文档对象Document

		Document document = builder.parse(file);

		return document;
	}

	// 回写操作
	public static void domToFile(Document document, File file)throws TransformerException {
		TransformerFactory factory = TransformerFactory.newInstance();
		Transformer tf = factory.newTransformer();
		tf.transform(new DOMSource(document), new StreamResult(file));
	}
}


       
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值