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

java dom xml解析的操作

xml文件:

<?xml version="1.0" encoding="utf-8" standalone="no"?>
<students>
    <student>
        <name>雷军</name>
        <age>马化腾</age>
        <phone>111</phone>
    </student>
    <student>
        <name>马化腾</name>
        <age>22</age>
        <phone>222</phone>
    </student>
</students>

读取的方法:

/**
     * 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("回写结束");

    }

}
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值