java操作xml文件(增删改查)

创建XML文件

/**
     * 创建xml方法
     */
    public  void createXml(String filePath){
        try {
            // 创建解析器工厂
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = factory.newDocumentBuilder();
            Document document = db.newDocument();
            // 不显示standalone="no"
            document.setXmlStandalone(true);
            Element solution = document.createElement("Solution");
            // 将bookstore节点(已包含book)添加到dom树中
            document.appendChild(solution);

            // 创建TransformerFactory对象
            TransformerFactory tff = TransformerFactory.newInstance();
            // 创建 Transformer对象
            Transformer tf = tff.newTransformer();

            // 输出内容是否使用换行
            tf.setOutputProperty(OutputKeys.INDENT, "yes");
            // 创建xml文件并写入内容
            tf.transform(new DOMSource(document), new StreamResult(new File("E://"+filePath+".xml")));
            System.out.println("生成"+filePath+".xml成功");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("生成"+filePath+".xml失败");
        }
    }

更新XML文件

  public  void updateXML(CSolution cSolution,String xmlPath) throws ParserConfigurationException, IOException, SAXException, TransformerException {
        File file = new File(xmlPath);//Persons.xml文件绝对路径
        //①获得解析器DocumentBuilder的工厂实例DocumentBuilderFactory  然后拿到DocumentBuilder对象
        DocumentBuilder newDocumentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        //②获取一个与磁盘文件关联的非空Document对象
        Document doc = newDocumentBuilder.parse(file);
        //③通过文档对象获得该文档对象的根节点
        Element root = doc.getDocumentElement();
        //查找指定节点
        //通过根节点获得子节点
        NodeList personList = root.getElementsByTagName("SolutionItem");
        for (int i = 0; i <personList.getLength() ; i++) {
            Node item = personList.item(i);
           Element element=(Element)item;
            String id = element.getAttribute("id");
            if(cSolution.getId().equals(id)){
                Field[] fields = cSolution.getClass().getDeclaredFields();
                String[] fieldNames=getFiledName(cSolution);
                for (String fieldName : fieldNames) {
                    Object value = getFieldValueByName(fieldName,cSolution);
                    NodeList nameList = element.getElementsByTagName(fieldName);
                    if(oConvertUtils.isNotEmpty(value)){
                        nameList.item(0).setTextContent(value.toString());
                    }
                }
            }
        }

        //这里获取第1个节点
       /* Node item = personList.item(0);
//		System.out.println(item.getTextContent());
        Element personElement = (Element) item;
        //获取personElement下面的子节点
        NodeList nameList = personElement.getElementsByTagName("name");
//		System.out.println(nameList.item(0).getTextContent());
        //修改
        nameList.item(0).setTextContent("火神");*/

        //注意:XML文件是被加载到内存中 修改也是在内存中 ==》因此需要将内存中的数据同步到磁盘中
        /*
         * static TransformerFactory newInstance():获取 TransformerFactory 的新实例。
         * abstract  Transformer newTransformer():创建执行从 Source 到 Result 的复制的新 Transformer。
         * abstract  void transform(Source xmlSource, Result outputTarget):将 XML Source 转换为 Result。
         */
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        //DOMSource source = new DOMSource(doc);

        Source source = new DOMSource(doc);
        //StreamResult result = new StreamResult();
        Result result = new StreamResult(file);
        transformer.transform(source, result);//将 XML==>Source 转换为 Result
    }

新增XML文件

  /**
     * 新增xml节点内容
     */
    public  void addXML(CSolution cSolution,String xmlPath) throws IOException, SAXException, ParserConfigurationException, TransformerException {
        File file = new File(xmlPath);//Persons.xml文件绝对路径
        //①获得解析器DocumentBuilder的工厂实例DocumentBuilderFactory  然后拿到DocumentBuilder对象
        DocumentBuilder newDocumentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        //②获取一个与磁盘文件关联的非空Document对象
        Document doc = newDocumentBuilder.parse(file);
        //③通过文档对象获得该文档对象的根节点
        Element root = doc.getDocumentElement();

        Element book = doc.createElement("SolutionItem");

        Field[] fields = cSolution.getClass().getDeclaredFields();
        String[] fieldNames=getFiledName(cSolution);
        for (String fieldName : fieldNames) {
            Element name = doc.createElement(fieldName);
            Object value = getFieldValueByName(fieldName,cSolution);
            if(oConvertUtils.isNotEmpty(value)){
                name.setTextContent(value.toString());
            }
            book.appendChild(name);
        }
        // 不显示内容 name.setNodeValue("不好使");

        // 为book节点添加属性
        book.setAttribute("id", cSolution.getId());
        root.appendChild(book);
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        //DOMSource source = new DOMSource(doc);
        Source source = new DOMSource(doc);
        //StreamResult result = new StreamResult();
        Result result = new StreamResult(file);
        transformer.transform(source, result);//将 XML==>Source 转换为 Result
    }

删除XML内容

  /**
     * 删除xml数据
     * @throws ParserConfigurationException
     * @throws IOException
     * @throws SAXException
     * @throws TransformerException
     */
    public  void deleteXML(String xid,String xmlPath) throws ParserConfigurationException, IOException, SAXException, TransformerException {
        {
            File file = new File(xmlPath);//Persons.xml文件绝对路径
            //①获得解析器DocumentBuilder的工厂实例DocumentBuilderFactory  然后拿到DocumentBuilder对象
            DocumentBuilder newDocumentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            //②获取一个与磁盘文件关联的非空Document对象
            Document doc = newDocumentBuilder.parse(file);
            //③通过文档对象获得该文档对象的根节点
            Element root = doc.getDocumentElement();
            //查找指定节点
            //通过根节点获得子节点
            NodeList personList = root.getElementsByTagName("SolutionItem");
            for (int i = 0; i < personList.getLength(); i++) {
                Node item = personList.item(i);
                Element element = (Element) item;
                String id = element.getAttribute("id");
                    if (xid.equals(id)) {
                        root.removeChild(item);
                    }
            }

            //这里获取第1个节点
       /* Node item = personList.item(0);
//		System.out.println(item.getTextContent());
        Element personElement = (Element) item;
        //获取personElement下面的子节点
        NodeList nameList = personElement.getElementsByTagName("name");
//		System.out.println(nameList.item(0).getTextContent());
        //修改
        nameList.item(0).setTextContent("火神");*/

            //注意:XML文件是被加载到内存中 修改也是在内存中 ==》因此需要将内存中的数据同步到磁盘中
            /*
             * static TransformerFactory newInstance():获取 TransformerFactory 的新实例。
             * abstract  Transformer newTransformer():创建执行从 Source 到 Result 的复制的新 Transformer。
             * abstract  void transform(Source xmlSource, Result outputTarget):将 XML Source 转换为 Result。
             */
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            //DOMSource source = new DOMSource(doc);

            Source source = new DOMSource(doc);
            //StreamResult result = new StreamResult();
            Result result = new StreamResult(file);
            transformer.transform(source, result);//将 XML==>Source 转换为 Result
        }

记录一下

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值