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>
版权声明:本文标题:java删除xml文件内容 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.elefans.com/dianzi/1729844257a1214947.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论