Dom 解析xml 读取,添加,删除操作

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hekai7217/article/details/82391180

java dom xml解析的操作

读取的方法:

/**
     * Dom 读取 xml 操作
     * 
     * @throws Exception
     */
    @Test
    public void read() throws Exception {

        // 获取 解析工厂
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

        // 通过工厂 获取 解析器
        DocumentBuilder db = dbf.newDocumentBuilder();

        // 解析 xml 获取doc
        Document doc = db.parse(new File("src/stu.xml"));

        // 获取根 节点
        Element root = doc.getDocumentElement();

        // 获取元素
        NodeList childNodes = root.getElementsByTagName("student");

        for (int i = 0; i < childNodes.getLength(); i++) {

            // 获取 student 节点
            Node node = childNodes.item(i);

            NodeList nodeList = node.getChildNodes();
            // 获取 student 下面的子节点
            for (int j = 0; j < nodeList.getLength(); j++) {

                Node item = nodeList.item(j);

                // 是标签
                if (item.getNodeType() == Node.ELEMENT_NODE) {

                    if (item.getNodeName().equals("name")) {
                        System.out.println(item.getTextContent());
                    }
                    if (item.getNodeName().equals("age")) {
                        System.out.println(item.getTextContent());
                    }
                    if (item.getNodeName().equals("phone")) {
                        System.out.println(item.getTextContent());
                    }
                }
            }
        }
    }

删除的方法:

 /**
     * 删除操作
     */
    @Test
    public void delete() {

        try {
            Document doc = DomUtils.getDoc("src/stu.xml");

            // 获取根节点
            Element root = doc.getDocumentElement();

            // 获取 student 节点
            Node item = root.getElementsByTagName("student").item(0);

            // 移除操作
            root.removeChild(item);

            // 回写 操作

            // 回写工厂
            TransformerFactory tff = TransformerFactory.newInstance();

            // 回写器
            Transformer tf = tff.newTransformer();

            // 资源
            DOMSource doms = new DOMSource(doc);

            OutputStream os = new FileOutputStream("src/stu.xml");
            // 流
            StreamResult sr = new StreamResult(os);
            // 回写 资源 流
            tf.transform(doms, sr);

            System.out.println("回写结束");

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

添加节点的操作:

/**
     * 添加节点的操作
     */
    @Test
    public void insert() {

        String path = "src/stu.xml";
        try {

            // 获取 doc
            Document doc = DomUtils.getDoc(path);

            // 获取 根目录
            Element root = doc.getDocumentElement();

            Element stu = doc.createElement("student");

            // 创建节点
            Element nameNode = doc.createElement("name");
            // 创建文字节点
            Text nameText = doc.createTextNode("马化腾");

            // 添加 文字节点
            nameNode.appendChild(nameText);

            stu.appendChild(nameNode);

            // 创建节点
            Element ageNode = doc.createElement("age");
            // 创建文字节点
            Text ageText = doc.createTextNode("33");

            // 添加 文字节点
            ageNode.appendChild(ageText);

            stu.appendChild(ageNode);

            // 创建节点
            Element phoneNode = doc.createElement("phone");
            // 创建文字节点
            Text phoneText = doc.createTextNode("4444");

            // 添加 文字节点
            phoneNode.appendChild(phoneText);

            stu.appendChild(phoneNode);

            // 添加到根节点
            root.appendChild(stu);

            // 回写操作
            DomUtils.xmlWrite(doc, path);

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

封装的工具类:

public class DomUtils {

    /**
     * 解析 获取 doc的操作
     * 
     * @param path
     * @return
     * @throws Exception
     */
    public static Document getDoc(String path) throws Exception {

        // 获取 工厂
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

        // 获取解析工厂
        DocumentBuilder db = dbf.newDocumentBuilder();

        // 解析 xml 获取doc
        return db.parse(new File(path));
    }

    /**
     * 回写操作
     * 
     * @param doc
     * @param path
     * @throws Exception
     */
    public static void xmlWrite(Document doc, String path) throws Exception {

        // 回写工厂
        TransformerFactory tff = TransformerFactory.newInstance();

        Transformer tf = tff.newTransformer();

        DOMSource doms = new DOMSource(doc);

        OutputStream os = new FileOutputStream(path);
        StreamResult sr = new StreamResult(os);
        // 回写
        tf.transform(doms, sr);

        System.out.println("回写结束");

    }

}

猜你喜欢

转载自blog.csdn.net/hekai7217/article/details/82391180