java dom4j 去除空行_如何从XML文件中删除多余的空行?
總之;我在XML文件中生成了很多空行,并且我正在尋找一種方法將它們作為一種傾斜文件的方式來刪除它們。我怎樣才能做到這一點 ?如何從XML文件中刪除多余的空行?
有關(guān)詳細說明,目前,我有這個XML文件:
path1
path2
path3
path4
我用這個Java代碼來刪除所有標簽,并添加新的來代替:
public void savePaths(String recentFilePath) {
ArrayList newPaths = getNewRecentPaths();
Document recentDomObject = getXMLFile(recentFilePath); // Get the element.
NodeList pathNodes = recentDomObject.getElementsByTagName("path"); // Get all nodes.
//1. Remove all old path nodes :
for (int i = pathNodes.getLength() - 1; i >= 0; i--) {
Element pathNode = (Element)pathNodes.item(i);
pathNode.getParentNode().removeChild(pathNode);
}
//2. Save all new paths :
Element pathsElement = (Element)recentDomObject.getElementsByTagName("paths").item(0); // Get the first node.
for(String newPath: newPaths) {
Element newPathElement = recentDomObject.createElement("path");
newPathElement.setTextContent(newPath);
pathsElement.appendChild(newPathElement);
}
//3. Save the XML changes :
saveXMLFile(recentFilePath, recentDomObject);
}
執(zhí)行這種方法多次之后,我得到一個XML用正確的結(jié)果文件,但有許多空行的“路徑”標簽后的第一個“路徑”標簽之前,像這樣:
path5
path6
path7
任何人知道如何解決這個問題?
-------------------------------------------編輯:添加getXMLFile(...),saveXMLFile(...)代碼。
public Document getXMLFile(String filePath) {
File xmlFile = new File(filePath);
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document domObject = db.parse(xmlFile);
domObject.getDocumentElement().normalize();
return domObject;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void saveXMLFile(String filePath, Document domObject) {
File xmlOutputFile = null;
FileOutputStream fos = null;
try {
xmlOutputFile = new File(filePath);
fos = new FileOutputStream(xmlOutputFile);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
DOMSource xmlSource = new DOMSource(domObject);
StreamResult xmlResult = new StreamResult(fos);
transformer.transform(xmlSource, xmlResult); // Save the XML file.
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
} finally {
if (fos != null)
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2012-10-01
Brad
+0
這可能是有益的,看看你的saveXMLFile方法的內(nèi)容。 –
+0
@Markus ...當然,我編輯了這個問題。 –
+1
您可以看看[使用Java刪除XML中的節(jié)點和空行](http://techxplorer.com/2010/05/24/deleting-nodes-and-empty-lines-in-xml-using-java /)和http://stackoverflow.com/questions/7190639/remove-all-blank-spaces-and-empty-lines –
總結(jié)
以上是生活随笔為你收集整理的java dom4j 去除空行_如何从XML文件中删除多余的空行?的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java直接量_Java教程:Java直
- 下一篇: mysql主备模型_MySQL主从复制