dom4j替换xml节点元素
package test;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;使用dom4j解析xml文件
import java.util.List;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
public class ReplaceElement {
private static org.dom4j.Document replaceElement(File newXML,
org.dom4j.Element connectionElement) {
org.dom4j.Document doc = getDoc(newXML);
org.dom4j.Element rootElement = RootElement();
org.dom4j.Element element = rootElement.element("data-sources");
List<Element> content = Parent().content();
int indexOf = content.indexOf(element);
content.add(indexOf, connectionElement);
return doc;
}
private static boolean replaceConnection(File oldXML, File newXML) {
try {
writeXML(replaceElement(newXML, getSubElement(oldXML)),
return true;
} catch (Exception e) {
return false;
}
}
private static void writeXML(org.dom4j.Document doc, String fileName) {
try {
XMLWriter writer = new XMLWriter(new FileWriter(fileName));
writer.write(doc);
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static org.dom4j.Document getDoc(File file) {
SAXReader reader = new SAXReader();
org.dom4j.Document doc = null;
try {
doc = ad(file);
} catch (DocumentException e) {
e.printStackTrace();
}
return doc;
}
private static org.dom4j.Element getSubElement(File XML) {
org.dom4j.Document doc = getDoc(XML);
org.dom4j.Element rootElement = RootElement();
org.dom4j.Element element = rootElement.element("data-sources");
return element;
}
public static void main(String[] args) {
replaceConnection(new File("your source file"), new File("your need replace file")); }
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。