我正在尝试编写一个具有正确缩进的XML文件。这是我的代码:
public class WebVideo {
private final String C_XMLFILEPATH = "resources/video.xml";
private String itemId;
private String videoPath;
public WebVideo(long itemId, String videoPath) {
this.itemId = Long.toString(itemId);
this.videoPath = videoPath;
}
public void saveVideo() throws ParserConfigurationException, IOException,
TransformerFactoryConfigurationError, TransformerException,
SAXException {
File xmlFile = new File(C_XMLFILEPATH);
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory
.newDocumentBuilder();
Document document = null;
Element rootElement = null;
if (xmlFile.exists()) {
document = documentBuilder.parse(xmlFile);
rootElement = document.getDocumentElement();
} else {
document = documentBuilder.newDocument();
rootElement = document.createElement("Videos");
document.appendChild(rootElement);
}
Element itemElement = document.createElement("Video");
rootElement.appendChild(itemElement);
Element idElement = document.createElement("Id");
Text id = document.createTextNode(itemId);
idElement.appendChild(id);
itemElement.appendChild(idElement);
Element pathElement = document.createElement("Path");
Text path = document.createTextNode(videoPath);
pathElement.appendChild(path);
itemElement.appendChild(pathElement);
Transformer transformer = TransformerFactory.newInstance()
.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(
"{http://xml.apache.org/xslt}indent-amount", "4");
StreamResult streamResult = new StreamResult(new StringWriter());
DOMSource domSource = new DOMSource(document);
transformer.transform(domSource, streamResult);
String xmlString = streamResult.getWriter().toString();
BufferedWriter bufferedWriter = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(xmlFile)));
bufferedWriter.write(xmlString);
bufferedWriter.flush();
bufferedWriter.close();
}
}
一切都没问题,但是如果你仔细观察输出的XML文件,在我添加新元素时会出现问题。输出的XML文件在这里:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Videos>
<Video>
<Id>1</Id>
<Path>path</Path>
</Video>
<Video>
<Id>2</Id>
<Path>path</Path>
</Video>
</Videos>
标签与 <pre>
标签在同一缩进级别,如何解决这个问题?谢谢。