如何从XML文件中删除多余的空行?
简而言之; 我在XML文件中生成了许多空行,并且我正在寻找一种删除它们的方法,以作为倾斜文件的一种方法。我怎样才能做到这一点 ?
详细说明;我目前有这个XML文件:
<recent> <paths>
<path>path1</path>
<path>path2</path>
<path>path3</path>
<path>path4</path>
</paths>
</recent>
我使用此Java代码删除所有标签,并添加新标签:
public void savePaths( String recentFilePath ) { ArrayList<String> newPaths = getNewRecentPaths();
Document recentDomObject = getXMLFile( recentFilePath ); // Get the <recent> element.
NodeList pathNodes = recentDomObject.getElementsByTagName( "path" ); // Get all <path> 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 <paths> node.
for( String newPath: newPaths ) {
Element newPathElement = recentDomObject.createElement( "path" );
newPathElement.setTextContent( newPath );
pathsElement.appendChild( newPathElement );
}
//3. Save the XML changes :
saveXMLFile( recentFilePath, recentDomObject );
}
在多次执行此方法后,我得到了一个XML文件,其结果正确,但是在“ paths”标记之后和第一个“ path”标记之前有许多空行,如下所示:
<recent> <paths>
<path>path5</path>
<path>path6</path>
<path>path7</path>
</paths>
</recent>
有人知道该如何解决吗?
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();
}
}
}
回答:
在删除所有旧的“路径”节点之后,我可以通过使用以下代码来解决此问题:
while( pathsElement.hasChildNodes() ) pathsElement.removeChild( pathsElement.getFirstChild() );
这将删除XML文件中所有生成的空白区域。
以上是 如何从XML文件中删除多余的空行? 的全部内容, 来源链接: utcz.com/qa/408891.html