由于与此主题相关的所有其他问题都涉及特定的编程问题(例如,'当我尝试这个时我得到NullPointerException而且')并且答案正在修复编程错误,这里是以下问题的简单解决方案:
如何使用DOM4J从XML文件中删除节点?
答案 0 :(得分:5)
假设您已经拥有要删除的节点:
Document document = node.getDocument();
node.detach();
XMLWriter writer = new XMLWriter(new FileWriter(document.getPath() + document.getName()), OutputFormat.createPrettyPrint());
writer.write(document);
writer.close();
省略了try-catch语句。
简短说明:
有关更完整的示例,请参阅JUnit测试:
@Test
public void dom4j() throws DocumentException, IOException {
String absolutePath = Paths.get(PATH_TO_XML).toAbsolutePath().toString();
SAXReader reader = new SAXReader();
Document document = reader.read(absolutePath);
Node node = document.selectSingleNode(XPATH_TO_NODE);
node.detach();
XMLWriter writer = new XMLWriter(new FileWriter(absolutePath), OutputFormat.createPrettyPrint());
writer.write(document);
writer.close();
}
有关DOM4J的更多信息,请参阅: http://dom4j.sourceforge.net/dom4j-1.6.1/guide.html
有关XPath语法的更多信息:http://www.w3schools.com/xsl/xpath_syntax.asp
答案 1 :(得分:0)
要使用XPath删除节点,您可以在vtd-xml
中执行此操作import com.ximpleware.*;
import java.io.*;
public class removeElement {
public static void main(String s[]) throws VTDException,IOException{
VTDGen vg = new VTDGen();
if (!vg.parseFile("input.xml", false))
return;
VTDNav vn = vg.getNav();
XMLModifier xm = new XMLModifier(vn);
AutoPilot ap = new AutoPilot(vn);
ap.selectXPath("/ClOrdIDS/ClOrdID[@id='3']");
int i=0;
while((i=ap.evalXPath())!=-1){
xm.remove();
}
xm.output("output.xml");
}
}