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("删除成功");
        }
    
    }
    
    
  • 相关阅读:
    自己学习编程时间比较短,现在把一下自己以前刚刚接触C++时的程序上传一下,有空可以看看
    Scene is unreachable due to lack of entry points and does not have an identifier for runtime access via -instantiateViewControllerWithIdentifier解决办法
    CocosPods 每次install pod 都卡在analyzing
    NSArray,NSMutable和NSSet,NSMutableSet和NSDictionary,NSMutableDictionary用法
    准备离职,工作的一些细节记录
    SpriteBuilder 不能对设置spriteframe的sprite进行设置dynamic Physics解决办法
    SpriteBuilder 不能 Portrait
    LLVM和GCC的区别
    cocos2d 3.3 安装教程
    浅谈 关于ARC循环引用得问题
  • 原文地址:https://www.cnblogs.com/wzh7/p/12873365.html
Copyright © 2011-2022 走看看