使用Java结合Dom4j和XPath批量处理XML文件的大概逻辑总结:
- 如果不使用maven,需要下载Dom4j和jaxen Jar包,虽然dom4j支持xpath语法,但仍需要引入jaxen依赖,否则运行会报错误。附上jar包下载地址:https://mvnrepository.com/artifact/org.dom4j/dom4j
public class DeleModifyXml {
public static void main(String[] args) {
modifyXML();
deleteXML();
}
public static Document XMLInputRead() throws DocumentException {
//创建解析器
SAXReader saxReader = new SAXReader();
//类路径加载
InputStream reasourceAsStream = DeleModifyXml.class.getClassLoader()
.getResourceAsStream("文件名");
Document document = saxReader.read(reasourceAsStream);
return document;
}
public static void XMLWriteOutPut(Document doc) throws Exception {
//持久化流
FileOutputStream fos = new FileOutputStream("文件名1");
XMLWriter writer = new XMLWriter(fos);
writer.write(doc);
writer.close();
}
public static void deleteXML()
{
try {
Document document = XMLInputRead();
//Xpath全文匹配节点
List<Node> ChildrenNode1 = document.selectNodes("//*[name()='节点name']");
List<Node> ChildrenNode2 = document.selectNodes("//*[name()='节点name2']");
for(int i = 0; i < ChildrenNode1.size(); i++)
{
Element childElement = (Element)ChildrenNode1.get(i);
List<Node> childrenNode = childElement.selectNodes("*[name()='节点名3']");
if(childrenNode.size() !=0){
Element childNodeElement = (Element)childrenNode.get(0);
//利用父节点去删除子节点
childElement.remove(ChildNodeElement);
}
}
XMLWriteOutPut(document);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void modifyXML(){
try {
Document document = XMLInputRead();
List<Node> theNodes = document.selectNodes("//*[name()='节点01']")
if(theNodes.size() !=0)
{
for(int i=0;i<theNodes.size();i++)
{
Element child = (Element)theNodes.get(i);
// System.out.println(child.getName)
List<Element> childrenone = child.selectNodes("*[name()='节点名']")
String Parameter = childrenone.get(0).getText();
/*
* 多层嵌套继续套就行
*/
}
}
//Xpath全文匹配节点
List<Node> ChildrenNode1 = document.selectNodes("//*[name()='节点name']");
List<Node> ChildrenNode2 = document.selectNodes("//*[name()='节点name2']");
for(int i = 0; i < ChildrenNode1.size(); i++)
{
Element childElement = (Element)ChildrenNode1.get(i);
List<Node> childrenNode = childElement.selectNodes("*[name()='节点名3']");
if(childrenNode.size() !=0)
{
Element childNodeElement = (Element)childrenNode.get(0);
//利用父节点去删除子节点
childElement.remove(ChildNodeElement);
}
}
XMLWriteOutPut(document);
} catch (Exception e) {
e.printStackTrace();
}
}
}
- 建议:将各个不同的功能模块封装起来,以备迭代使用,遵循高内聚低耦合开发原则。