admin管理员组

文章数量:1660067

一、依赖

  <dependency>
      <groupId>org.dom4j</groupId>
      <artifactId>dom4j</artifactId>
      <version>2.1.3</version>
      <scope>compile</scope>
    </dependency>

 二、待操作XML文件

<mymvc>
    <actions>
        <action name="list" class="controller.List">
            <result name="toListJSP">
                /list.jsp
            </result>
            <result name="toShowUserinfoList" type="'redirect">
                showUserinfoList.ghy
            </result>
        </action>
        <action name="showUserinfoList" class="controller.ShowUserinfoList">
            <result name="toShowUserinfoListJSP">
                /showUserinfoList.jsp
            </result>
        </action>
    </actions>
</mymvc>

三、操作节点

package org.example.xmltest;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

public class Delete {
    public static void main(String[] args) throws DocumentException, IOException {
        SAXReader reader = new SAXReader();
        //1、读取XML文件
        Document document = reader.read(reader.getClass().getResourceAsStream("/struts.xml"));
        //2、获取根元素
        Element rootElement = document.getRootElement();
        //获取根元素的所有子元素
        List<Element> rootChildren = rootElement.elements();
        for (Element child : rootChildren) {
            List<Element> childChildren = child.elements();
            if (childChildren != null && childChildren.size() > 0) {
                for (Element childChild : childChildren) {
                    //获取name属性
                    Attribute name = childChild.attribute("name");
                    if (name != null) {
                        //如果属性存在,删除
                        childChild.remove(name);
                    }
                    List<Element> elements = childChild.elements();
                    for (Element element : elements) {
                        //删除子元素
                        childChild.remove(element);
                    }
                }
            }
        }
        //创建输出格式
        OutputFormat format = OutputFormat.createPrettyPrint();
        //XML写入工具
        XMLWriter writer = new XMLWriter(new FileWriter("delete.xml"), format);
        //写入文档至XML文件
        writer.write(document);
        //关闭流
        writer.close();
    }
}

四、删除后节点及属性后生成的文件

<?xml version="1.0" encoding="UTF-8"?>

<mymvc> 
  <actions> 
    <action class="controller.List"></action>  
    <action class="controller.ShowUserinfoList"></action> 
  </actions> 
</mymvc>

 

本文标签: 文件内容JavaXML