Java的xml解析器

1、jaxp

是javase的一部分,就是jdk中的一部分,javax.xml.parsers包

1.1、dom方式解析xml
    DocumentBuilder
    DocumentBuilderFactory

package demo;

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

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 java.io.IOException;

public class AppDom {
    public static void main(String[] args) throws Exception {
        queryList();
        //insertTag();
        //updateTag();
        //deleteTag();
    }


    public static void queryList() throws ParserConfigurationException, IOException, SAXException {
        //1、创建解析器工厂
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();

        //2、创建解析器
        DocumentBuilder builder = builderFactory.newDocumentBuilder();

        //3、解析xml返回document
        Document doc = builder.parse("./src/main/resources/persons.xml");

        //4、递归遍历
        RecursiveNode(doc);
    }

    private static void RecursiveNode(Node node) {
        //判断是元素类型才打印
        if (node.getNodeType()==Node.ELEMENT_NODE){
            System.out.println(node.getNodeName());
        }

        //得到当前节点的子节点集合
        NodeList nodeList = node.getChildNodes();

        //遍历
        for (int i= 0;i<nodeList.getLength();i++){
            RecursiveNode(nodeList.item(i));
        }
    }

    public static void insertTag() throws Exception{
        //1、创建解析器工厂
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        //2、创建解析器
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        //3、解析xml,返回document
        Document doc = builder.parse("./src/main/resources/persons.xml");
        //4、得到第一个person标签
        Node person = doc.getElementsByTagName("person").item(0);
        //5、创建sex标签 createElement
        Element sex = doc.createElement("sex");
        //6、创建文本 createTextNode
        Text text = doc.createTextNode("男");
        //7、把文本添加到sex标签下面 appendChild
        sex.appendChild(text);
        //8、把sex标签添加到第一个person下面
        person.appendChild(sex);
        //9、回写
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.transform(new DOMSource(doc),new StreamResult("./src/main/resources/persons.xml"));
    }

    private static void updateTag() throws Exception {
        //1、创建解析器工厂
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        //2、创建解析器
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        //3、解析xml,返回document
        Document doc = builder.parse("./src/main/resources/persons.xml");
        //4、得到第一个sex标签
        Node sex = doc.getElementsByTagName("sex").item(0);
        //5、修改sex标签 setTextContext()
        sex.setTextContent("女");
        //6、回写
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.transform(new DOMSource(doc),new StreamResult("./src/main/resources/persons.xml"));
    }

    public static void deleteTag() throws Exception {
        //1、创建解析器工厂
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        //2、创建解析器
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        //3、解析xml,返回document
        Document doc = builder.parse("./src/main/resources/persons.xml");
        //4、得到第一个sex标签
        Node sex = doc.getElementsByTagName("sex").item(0);
        //5、获取sex的父节点
        Node person = sex.getParentNode();
        //6、使用父节点删除 removeChild()
        person.removeChild(sex);
        //7、回写
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.transform(new DOMSource(doc),new StreamResult("./src/main/resources/persons.xml"));
    }
}

 1.2、sax方式解析xml

    SAXParser
    SAXParserFactory

package demo;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

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

public class AppSax {
    public static void main(String[] args) throws Exception {
        /*
         *  1、创建解析器工厂
         *  2、创建解析器
         *  3、执行parse()
         *  4、继承DefaultHandler,重写三个方法
         *  5、
         */
        //1、创建解析器工厂
        SAXParserFactory factory = SAXParserFactory.newInstance();
        //2、创建解析器
        SAXParser parser =factory.newSAXParser();
        //3、执行parse()
        parser.parse("./src/main/resources/book.xml",new PrintNameHandler());
    }
}

/**
 * 打印出所有name标签的值
 */
class PrintNameHandler extends DefaultHandler{
    boolean flag = false;
    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        if ("name".equals(qName)){
            flag = true;
        }
    }

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

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        if ("name".equals(qName)){
            flag = false;
        }
    }
}

/**
 * 打印xml处理器
 */
class PrintXMLHandler extends DefaultHandler {
    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        System.out.print("<"+qName+">");
    }

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

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

2、dom4j

2.1、sax方式

posted @ 2020-11-20 22:22  沉沉沉几许  阅读(394)  评论(0编辑  收藏  举报