I want to remove a line an xml file after writing in it
I have this code ,that parse a file xml ,I want ,after writing in this file,to remove the second line ,but I don't know how to do it?
this is my code:
File file = new File("C:\\Documents and Settings\\My Documents\\test.xml");
dos = new DataOutputStream(new FileOutputStream(file));
dos.writeBytes(var2); //after writing I want to remove the second line
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);
doc.getDocumentElement().normalize();
System.out.println("Root element " + doc.getDocumentElement().getNodeName());
NodeList nodeLst = doc.getElementsByTagName("step");
System.out.println("Information of all steps");
for (int s = 0; s < nodeLst.getLength(); s++) {
Node fstNode = nodeLst.item(s);
if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
Element fstElmnt = (Element) fstNode;
System.out.println("oooo"+fstElmnt.toString());
// NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("step");
String fst = fstElmnt.getAttribute("name");
System.out.println("name : "+fst); //display steps un step
}
开发者_如何学Go }
}
catch (Exception e) {
e.printStackTrace();
}
UPDATE
I want to remove a node that generate an error when I try to parse the file ,so I should remove this node before trying to parse the file
A "line" has no meaning in an XML file. It's perfectly legal for the file to contain no line breaks, or for it to break lines at arbitrary points (for example, between attributes).
Instead, you want to remove a particular element from the file, or remove text from the element (it's unclear from your question which you want). To do the former, you call Node.removeChild() on the parent. For the latter, you can call Node.setTextContent() with an empty string or null.
The trick is finding the node that you want to replace. It looks like you're walking through the DOM. However, a much more elegant approach is to use XPath.
精彩评论