적절한 들여 쓰기를 사용하여 XML 파일을 작성하려고합니다. 여기 내 코드는 다음과 같습니다.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>
태그는 태그와 동일한 들여 쓰기에 있습니다. 이 문제를 어떻게 해결할 수 있습니까? 감사합니다.
가능한 중복을 [어떻게 자바에서 꽤 인쇄 XML에?] (http://stackoverflow.com/questions/139076/how-to- pretty-print-xml-from-java) – ThomasRS