zoukankan      html  css  js  c++  java
  • XML之Dom解析实现增删改查

    DOM解析XML实现增删改查

    • 新建student.xml
    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <students>
        <student id="0">
            <name>wzh</name>
            <age>18</age>
            <sex>男</sex>
        </student>
        <student id="1">
            <name>lld</name>
            <age>20</age>
            <sex>女</sex>
        </student>
    </students>
    
    
    • 新建一个类DomParseXml
    • init方法初始化dom
        //创建DOM对象
        private static Document init() throws Exception {
            //借助字节输入流从磁盘获取xml文档到流中
            FileInputStream fileInputStream = new FileInputStream("src/com/bosssoft/hr/train/xml/student.xml");
            //得到DOM工厂实例对象
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            //从工厂中获取DOM解析工具
            DocumentBuilder documentBuilder = factory.newDocumentBuilder();
            Document parse = documentBuilder.parse(fileInputStream);
            return parse;
        }
    
    
    • saveXml对修改的dom进行保存
        //保存xml
        public static void saveXML(Document document,String path) throws TransformerException {
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            transformerFactory.setAttribute("indent-number", 4);
            Transformer transformer = transformerFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "YES");
            transformer.transform(new DOMSource(document),new StreamResult(xmlPath+path));
        }
    
    • 查询
    //Dom解析,查询
        public static void queryAll() throws Exception {
            Document document = init();
            NodeList studentList = document.getElementsByTagName("student");
            //循环遍历
            for (int i=0; i< studentList.getLength(); i++){
                Node student = studentList.item(i);
                if(student.getNodeType() == Node.ELEMENT_NODE){
                    NodeList childNodes = student.getChildNodes();
                    for(int j =0; j< childNodes.getLength(); j++){
                        Node child = childNodes.item(j);
                        if(child.getNodeType() == Node.ELEMENT_NODE){
                            String textContent = child.getTextContent();
                            String nodeName = child.getNodeName();
                            System.out.println(nodeName + "-----"+ textContent);
                        }
                    }
                }
            }
        }
    
    • 修改
     //通过id查询student 然后修改对应信息
        public static void update(String id,String name,String path) throws Exception {
            Document document = init();
            NodeList StudentList = document.getElementsByTagName("student");
            for(int i = 0; i< StudentList.getLength(); i++){
                Node studentNode = StudentList.item(i);
                Element stu = (Element) studentNode;
                String id1 = stu.getAttribute("id");
                if(id != null && id.equals(id1)){
                    NodeList childNodes = studentNode.getChildNodes();
                    for(int j = 0; j < childNodes.getLength(); j++){
                        String nodeName = childNodes.item(j).getNodeName();
                        if(nodeName.equals("name")){
                            childNodes.item(j).getFirstChild().setTextContent(name);
                        }
                    }
                }
            }
            saveXML(document,path);
            System.out.println("修改成功");
        }
    
    • 增加
        //添加
        public static void add(String idvalue,String username ,String userage, String sex,String path) throws Exception {
            Document document = init();
            Element studentNode = document.createElement("student");
            studentNode.setAttribute("id",idvalue);
    
            Element nameNode = document.createElement("name");
            Element ageNode = document.createElement("age");
            Element sexNode = document.createElement("sex");
    
            nameNode.appendChild(document.createTextNode(username));
            ageNode.appendChild(document.createTextNode(userage));
            sexNode.appendChild(document.createTextNode(sex));
    
            studentNode.appendChild(nameNode);
            studentNode.appendChild(ageNode);
            studentNode.appendChild(sexNode);
    
            document.getElementsByTagName("students").item(0).appendChild(studentNode);
            saveXML(document,path);
            System.out.println("添加用户成功");
        }
    
    • 删除
     //删除 通过id查询 指定用户删除
        public static void  delete(String id,String path) throws Exception {
            Document document = init();
            NodeList StudentList = document.getElementsByTagName("student");
            for(int i = 0; i< StudentList.getLength(); i++){
                Node studentNode = StudentList.item(i);
                Element stu = (Element) studentNode;
                String id1 = stu.getAttribute("id");
                if(id != null && id.equals(id1)){
                    stu.getParentNode().removeChild(stu);
                }
            }
            saveXML(document,path);
            System.out.println("删除成功");
        }
    
    • 完整代码
    package com.bosssoft.hr.train.xml;
    
    import org.w3c.dom.*;
    
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.transform.*;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    import java.io.FileInputStream;
    
    
    
    /**
     * @作者 吴志鸿
     * @maven 3.6.3
     * @jdk 1.8
     */
    public class DomParseXml {
    
        private static String xmlPath = "src/com/bosssoft/hr/train/xml/";
    
        //创建DOM对象
        private static Document init() throws Exception {
            //借助字节输入流从磁盘获取xml文档到流中
            FileInputStream fileInputStream = new FileInputStream("src/com/bosssoft/hr/train/xml/student.xml");
            //得到DOM工厂实例对象
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            //从工厂中获取DOM解析工具
            DocumentBuilder documentBuilder = factory.newDocumentBuilder();
            Document parse = documentBuilder.parse(fileInputStream);
            return parse;
        }
    
        //Dom解析,查询
        public static void queryAll() throws Exception {
            Document document = init();
            NodeList studentList = document.getElementsByTagName("student");
            //循环遍历
            for (int i=0; i< studentList.getLength(); i++){
                Node student = studentList.item(i);
                if(student.getNodeType() == Node.ELEMENT_NODE){
                    NodeList childNodes = student.getChildNodes();
                    for(int j =0; j< childNodes.getLength(); j++){
                        Node child = childNodes.item(j);
                        if(child.getNodeType() == Node.ELEMENT_NODE){
                            String textContent = child.getTextContent();
                            String nodeName = child.getNodeName();
                            System.out.println(nodeName + "-----"+ textContent);
                        }
                    }
                }
            }
        }
    
        //保存xml
        public static void saveXML(Document document,String path) throws TransformerException {
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            transformerFactory.setAttribute("indent-number", 4);
            Transformer transformer = transformerFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "YES");
            transformer.transform(new DOMSource(document),new StreamResult(xmlPath+path));
        }
    
        //添加
        public static void add(String idvalue,String username ,String userage, String sex,String path) throws Exception {
            Document document = init();
            Element studentNode = document.createElement("student");
            studentNode.setAttribute("id",idvalue);
    
            Element nameNode = document.createElement("name");
            Element ageNode = document.createElement("age");
            Element sexNode = document.createElement("sex");
    
            nameNode.appendChild(document.createTextNode(username));
            ageNode.appendChild(document.createTextNode(userage));
            sexNode.appendChild(document.createTextNode(sex));
    
            studentNode.appendChild(nameNode);
            studentNode.appendChild(ageNode);
            studentNode.appendChild(sexNode);
    
            document.getElementsByTagName("students").item(0).appendChild(studentNode);
            saveXML(document,path);
            System.out.println("添加用户成功");
        }
    
        //通过id查询student 然后修改对应信息
        public static void update(String id,String name,String path) throws Exception {
            Document document = init();
            NodeList StudentList = document.getElementsByTagName("student");
            for(int i = 0; i< StudentList.getLength(); i++){
                Node studentNode = StudentList.item(i);
                Element stu = (Element) studentNode;
                String id1 = stu.getAttribute("id");
                if(id != null && id.equals(id1)){
                    NodeList childNodes = studentNode.getChildNodes();
                    for(int j = 0; j < childNodes.getLength(); j++){
                        String nodeName = childNodes.item(j).getNodeName();
                        if(nodeName.equals("name")){
                            childNodes.item(j).getFirstChild().setTextContent(name);
                        }
                    }
                }
            }
            saveXML(document,path);
            System.out.println("修改成功");
        }
    
        //删除 通过id查询 指定用户删除
        public static void  delete(String id,String path) throws Exception {
            Document document = init();
            NodeList StudentList = document.getElementsByTagName("student");
            for(int i = 0; i< StudentList.getLength(); i++){
                Node studentNode = StudentList.item(i);
                Element stu = (Element) studentNode;
                String id1 = stu.getAttribute("id");
                if(id != null && id.equals(id1)){
                    stu.getParentNode().removeChild(stu);
                }
            }
            saveXML(document,path);
            System.out.println("删除成功");
        }
    
    }
    
    
  • 相关阅读:
    韩式英语
    Daily dictation 听课笔记
    words with same pronunciation
    you will need to restart eclipse for the changes to take effect. would you like to restart now?
    glottal stop(britain fountain mountain)
    education 的发音
    第一次用Matlab 的lamada语句
    SVN的switch命令
    String的split
    SVN模型仓库中的资源从一个地方移动到另一个地方的办法(很久才解决)
  • 原文地址:https://www.cnblogs.com/wzh7/p/12873365.html
Copyright © 2011-2022 走看看