使用jaxp对XML文件进行dom解析

简述

使用jaxp对XML文件进行dom解析,实现增删查改和遍历,代码如下,每一行代码都有注释。
思路:和jsp的dom解析几乎一样,方法名都很像。这里先得到document对象,然后利用document的一些方法去实现想要的操作。Node接口是Element接口和Text接口的父接口。

xml文件

对应的xml文件如下(person.xml):

<?xml version="1.0" encoding="UTF-8" standalone="no"?><person>
    <P1>
        <name>AAA</name>
        <age>12</age>
    </P1>
    <P1>
        <name>BBB</name>
        <age>123</age>
    </P1>
</person>

代码

package xxy.test.jaxp;

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.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.SAXException;
/** * @author 许湘扬 2017-2-21 * @jaxp解析dom操作 * @注:增删操作,最后要回写,将在内存中的dom对象写入文件 */
public class TestJaxp {
    public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, TransformerException
    {
        //selectAll();
        //selectFirst();
        //addSex();
        //modifyNodeText();
        //delSex();
        listElement();
    }
    /* * 查询第一个name元素的值 */
    public static void selectFirst() throws ParserConfigurationException, IOException, SAXException
    {
        //1、创建解析器工厂
        DocumentBuilderFactory builderFactory=DocumentBuilderFactory.newInstance();
        //2、用解析器工厂创建解析器
        DocumentBuilder docuBuilder=builderFactory.newDocumentBuilder();
        //3、解析xml,返回document
        org.w3c.dom.Document document=docuBuilder.parse("src/person.xml");
        //4、得到所有name元素
        NodeList nodelist=document.getElementsByTagName("name");
        //5、获得第一个name元素
        Node name1=nodelist.item(0);
        //6、得到name元素里的文本
        String text=name1.getTextContent();
        System.out.println(text);
    }
    /* * 查询所有<name>节点 */
    public static void selectAll() throws ParserConfigurationException,
            SAXException, IOException 
    {
        //1、创建解析器工厂
        DocumentBuilderFactory builderFactory=DocumentBuilderFactory.newInstance();
        //2、用解析器工厂创建解析器
        DocumentBuilder docuBuilder=builderFactory.newDocumentBuilder();
        //3、解析xml,返回document
        org.w3c.dom.Document document=docuBuilder.parse("src/person.xml");
        //4、得到所有name元素
        NodeList nodelist=document.getElementsByTagName("name");
        //5、遍历NodeList
        for (int  i= 0;i  < nodelist.getLength(); i++)
        {
            //获得每一个name元素
            Node name1=nodelist.item(i);
            //得到name元素里的文本
            String text=name1.getTextContent();
            System.out.println(text);
        }
    }
    /* * 添加节点 * 这里:在第一个P1下面(末尾)添加 <sex>nv</sex> */
    public static void addSex() throws ParserConfigurationException, SAXException, IOException, TransformerException
    {
        //1、创建解析器工厂
        DocumentBuilderFactory builderFactory=DocumentBuilderFactory.newInstance();
        //2、用解析器工厂创建解析器
        DocumentBuilder docuBuilder=builderFactory.newDocumentBuilder();
        //3、解析xml,返回document
        org.w3c.dom.Document document=docuBuilder.parse("src/person.xml");
        //4、得到所有name元素
        NodeList nodelist=document.getElementsByTagName("P1");
        //获得第一个name元素
        Node firstP1=nodelist.item(0);
        //6、创建sex标签createElement(),创建文本标签 
        Text text1 =document.createTextNode("nv");
        Element sex1=document.createElement("sex");
        //7、把文本添加到sex下面 appendChild
        sex1.appendChild(text1);
        //8、把sex添加到第一个P1下面
        firstP1.appendChild(sex1);
        //9、回写xml 这一步骤保存好代码 以后直接复制使用,无需记忆
        TransformerFactory transformerFactory=TransformerFactory.newInstance();
        Transformer transformer=transformerFactory.newTransformer();
        transformer.transform(new DOMSource(document), new StreamResult("src/person.xml"));
    }
    /* * 修改节点 * 这里:以修改第一个sex为男,为例子 */
    public static void modifyNodeText() throws ParserConfigurationException, SAXException, IOException, TransformerException
    {
        //1、创建解析器工厂
        DocumentBuilderFactory builderFactory=DocumentBuilderFactory.newInstance();
        //2、用解析器工厂创建解析器
        DocumentBuilder docuBuilder=builderFactory.newDocumentBuilder();
        //3、解析xml,返回document
        org.w3c.dom.Document document=docuBuilder.parse("src/person.xml");
        //4、得到所有sex元素
        NodeList nodelist=document.getElementsByTagName("sex");
        //5、获得第一个sex元素
        Node sex=nodelist.item(0);
        //6、修改sex的内容
        sex.setTextContent("nan");
        //7、回写xml
        TransformerFactory transformerFactory=TransformerFactory.newInstance();
        Transformer transformer=transformerFactory.newTransformer();
        transformer.transform(new DOMSource(document), new StreamResult("src/person.xml"));
    }
    /* * 删除节点 * 这里:删除<sex>nv</sex> */
    public static void delSex() throws ParserConfigurationException, SAXException, IOException, TransformerException
    {
        //1、创建解析器工厂
        DocumentBuilderFactory builderFactory=DocumentBuilderFactory.newInstance();
        //2、用解析器工厂创建解析器
        DocumentBuilder docuBuilder=builderFactory.newDocumentBuilder();
        //3、解析xml,返回document
        org.w3c.dom.Document document=docuBuilder.parse("src/person.xml");
        //4、得到所有sex元素
        NodeList nodelist=document.getElementsByTagName("sex");
        //5、获得第一个sex元素
        Node sex=nodelist.item(0);
        //6、获取sex的父节点
        Node father=sex.getParentNode();
        //7、使用removeChild方法删除节点
        father.removeChild(sex);
        //8、回写xml
        TransformerFactory transformerFactory=TransformerFactory.newInstance();
        Transformer transformer=transformerFactory.newTransformer();
        transformer.transform(new DOMSource(document), new StreamResult("src/person.xml"));
    }
    /* * 遍历所有节点,把所有元素名称打印出来 */
    public static void listElement() throws SAXException, IOException, ParserConfigurationException
    {
        //1、创建解析器工厂
        DocumentBuilderFactory builderFactory=DocumentBuilderFactory.newInstance();
        //2、用解析器工厂创建解析器
        DocumentBuilder docuBuilder=builderFactory.newDocumentBuilder();
        //3、解析xml,返回document
        org.w3c.dom.Document document=docuBuilder.parse("src/person.xml");
        //4、递归遍历每一个节点
        list(document,0);
    }
    private static void list(Node node,int n) 
    {
        if (node.getNodeType()==Node.ELEMENT_NODE)//只输出元素名
        {
            for(int i=0;i<n-1;i++)//输出层次空格
                System.out.print(" ");
            System.out.println(node.getNodeName());
        }

        NodeList nodeList=node.getChildNodes();
        for(int i= 0;i<nodeList.getLength();i++)
        {
            list(nodeList.item(i),n+1);
        }   
    }
}

你可能感兴趣的:(java,xml,解析,dom)