XML学习笔记(三)---xml解析及具体实现

前端之家收集整理的这篇文章主要介绍了XML学习笔记(三)---xml解析及具体实现前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

概述

一个XML文件除了人去读写以外,程序也要去读写,利用程序去增删改查XML的过程就是XML编程。也就是利用程序对xml文件进行CRUD(Create、Read、Update、Delete)

两种解析思想

一张图片说明一切:

SAX解析的具体实现

package me.zipstream.sax;

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 SaxDemo1 {
    //工厂设计模式
    public static void main(String[] args) throws Exception{
        //1,获取解析器工厂
        SAXParserFactory factory = SAXParserFactory.newInstance();
        //2,通过工厂获取sax解析
        SAXParser parser = factory.newSAXParser();
        //3,获取读取器
        XMLReader reader = parser.getXMLReader();
        //4,注册事件处理器
        reader.setContentHandler(new MyContentHandler2());
        //5,解析xml
        reader.parse("book.xml");
    }
}

//适配器设计模式
//如何获取xml文件中某一个元素上的内容呢?
class MyContentHandler2 extends DefaultHandler{
    private String eleName = null;
    private int count = 0;

    @Override
    public void startElement(String uri,String localName,String name,Attributes attributes) throws SAXException {
        eleName = name;
    }

    @Override
    public void characters(char[] ch,int start,int length)
            throws SAXException {
        if ("书名".equals(eleName) && (++count)==2){
            System.out.println(new String(ch,start,length));
        }
    }

    @Override
    public void endElement(String uri,String name)
            throws SAXException {
        eleName = null;
    }
}

class MyContentHandler implements ContentHandler{

    @Override
    public void startDocument() throws SAXException {
        // TODO Auto-generated method stub
        System.out.println("文档解析开始了...");
    }

    @Override
    public void startElement(String uri,Attributes atts) throws SAXException {
        // TODO Auto-generated method stub
        System.out.println("发现了开始标签" + name);
    }

    @Override
    public void characters(char[] ch,int length)
            throws SAXException {
        // TODO Auto-generated method stub
        System.out.println(new String(ch,length));
    }

    @Override
    public void endElement(String uri,String name)
            throws SAXException {
        // TODO Auto-generated method stub
        System.out.println("发现了结束标签" + name);
    }

    @Override
    public void endDocument() throws SAXException {
        // TODO Auto-generated method stub
        System.out.println("文档解析结束了...");
    }

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

    }

    @Override
    public void ignorableWhitespace(char[] ch,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 startPrefixMapping(String prefix,String uri)
            throws SAXException {
        // TODO Auto-generated method stub

    }
}

DOM4J解析的具体实现

一种简单的方式:

package me.zipstream.dom4j;

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 Exception {
        //1,获取解析器
        SAXReader reader = new SAXReader();
        //2,获取代表整个文档的dom对象
        Document dom = reader.read("book.xml");
        //3,获取根节点
        Element root = dom.getRootElement();
        //4,获取书名进行打印
        String bookName = root.element("书").element("书名").getText();
        System.out.println(bookName);
    }
}

另一种方式,具体实现增删改查:

package me.zipstream.dom4j;

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

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.junit.Test;

public class Dom4jDemo2 {

    @Test
    public void attr() throws Exception{
        SAXReader reader = new SAXReader();
        Document dom = reader.read("book.xml");
        Element root = dom.getRootElement();

        Element bookEle = root.element("书");
        bookEle.addAttribute("出版社","机械工业出版社");
        String str = bookEle.attributeValue("出版社");
        System.out.println(str);
// Attribute attr = bookEle.attribute("出版社");
// attr.getParent().remove(attr);

        XMLWriter writer = new XMLWriter(new FileOutputStream("book.xml"),OutputFormat.createPrettyPrint());
        writer.write(dom);
        writer.close();
    }

    @Test
    public void delete() throws Exception{
        SAXReader reader = new SAXReader();
        Document dom = reader.read("book.xml");
        Element root = dom.getRootElement();

        Element price2Ele = root.element("书").element("特价");
        price2Ele.getParent().remove(price2Ele);

        XMLWriter writer = new XMLWriter(new FileOutputStream("book.xml"),OutputFormat.createPrettyPrint());
        writer.write(dom);
        writer.close();
    }

    @Test
    public void update() throws Exception{
        SAXReader reader = new SAXReader();
        Document dom = reader.read("book.xml");
        Element root = dom.getRootElement();

        root.element("书").element("特价").setText("4.0元");

        XMLWriter writer = new XMLWriter(new FileOutputStream("book.xml"),OutputFormat.createPrettyPrint());
        writer.write(dom);
        writer.close();
    }

    @Test
    public void add() throws Exception{
        SAXReader reader = new SAXReader();
        Document dom = reader.read("book.xml");
        Element root = dom.getRootElement();

        //凭空创建<特价>节点,设置标签
        Element price2Ele = DocumentHelper.createElement("特价");
        price2Ele.setText("40元");
        //获取标签<书>,将特价节点挂载上去
        root.element("书").add(price2Ele);

        //将内存中的dom树会写到xml文件中,从而使xml中的数据进行更新
        XMLWriter writer = new XMLWriter(new FileOutputStream("book.xml"),OutputFormat.createPrettyPrint());
        writer.write(dom);
        writer.close();
    }

    @Test
    public void find() throws Exception{
        SAXReader reader = new SAXReader();
        Document dom = reader.read("book.xml");
        Element root = dom.getRootElement();

        List<Element> list = root.elements();
        Element book2Ele = list.get(1);
        System.out.println(book2Ele.element("书名").getText());
    }
}

猜你在找的XML相关文章