从XML文件(DOM4J,JAVA)中删除节点
由于与此主题相关的所有其他问题都涉及到特定的编程问题(例如,“我尝试这个和那个时得到一个NullPointerException”),并且答案是修复编程错误,因此以下问题有一个简单的解决方案:从XML文件(DOM4J,JAVA)中删除节点,java,dom4j,Java,Dom4j,由于与此主题相关的所有其他问题都涉及到特定的编程问题(例如,“我尝试这个和那个时得到一个NullPointerException”),并且答案是修复编程错误,因此以下问题有一个简单的解决方案: 如何使用DOM4J从XML文件中删除节点?假设您已经拥有要删除的节点: Document document = node.getDocument(); node.detach(); XMLWriter writer = new XMLWriter(new FileWriter(docume
如何使用DOM4J从XML文件中删除节点?假设您已经拥有要删除的节点:
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语句被省略
简要说明:
@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的更多信息,请参阅:
有关XPath语法的更多信息:要使用XPath删除节点,您可以在
我非常欣赏新的解决方案:这不是问题的答案。这是如何使用XPath和vtd XML从XML文件中删除节点的问题的答案?或者标题从XML文件中删除节点(XPATH、VTD-XML、JAVA)
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");
}
}