1 需要添加dom4j的jar包https://mvnrepository.com/artifact/dom4j/dom4j
<!-- https://mvnrepository.com/artifact/dom4j/dom4j -->
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
我这里也用到了xpath,所以还得添加jaxen.jar包https://mvnrepository.com/artifact/jaxen/jaxen
<!-- https://mvnrepository.com/artifact/jaxen/jaxen -->
<dependency>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
<version>1.1.6</version>
</dependency>
2 工具类
package com.xzp.utils;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
/**
* @author xzp
* @date 2020-07-28 10:51:09
*/
public class XmlUtil {
/**
* 将一个xml文件中的节点复制到另一个xml文件
* @param targetFile 目标文件
* @param srcFile 源文件(要复制节点所在的文件)
* @throws Exception
*/
@SuppressWarnings("unchecked")
public static void placeSceneCopy(File targetFile, File srcFile) throws Exception {
XMLWriter writer = null;
try {
SAXReader saxReader = new SAXReader();
Document targetDoc = saxReader.read(targetFile);
Document otherDoc = saxReader.read(srcFile);
Element rootElement = targetDoc.getRootElement();
List<Element> elements = (List<Element>)otherDoc.selectNodes("//krpano/scene");//节点xpath路径
for(Element element : elements) {
rootElement.add(element.createCopy());
}
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");
writer = new XMLWriter(new FileOutputStream(targetFile), format);
writer.write(rootElement);
} finally {
if(writer != null) writer.close();
}
}
}
网友评论