我正在尝试使用适当的缩进编写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>
标记与标记位于同一缩进中。我怎么解决这个问题? 谢谢。
答案 0 :(得分:3)
检查此答案是否可以打印XML:How to pretty print XML from Java?
答案 1 :(得分:2)
如果您想要进行更多自定义,还可以创建自己的换行符格式。在追加实际子项之前附加换行文本:
Text lineBreak = doc.createTextNode("\n\t");
element.appendChild(lineBreak);
答案 2 :(得分:1)
某些XML库内置了漂亮的打印功能。例如dom4j有OutputFormat.createPrettyPrint()
- 请参阅http://dom4j.sourceforge.net/dom4j-1.6.1/guide.html#Writing_a_document_to_a_file
答案 3 :(得分:1)
public String formatXML(String input)
{
try
{
final InputSource src = new InputSource(new StringReader(input));
final Node document = DocumentBuilderFactory.newInstance()
.newDocumentBuilder().parse(src).getDocumentElement();
final DOMImplementationRegistry registry = DOMImplementationRegistry
.newInstance();
final DOMImplementationLS impl = (DOMImplementationLS) registry
.getDOMImplementation("LS");
final LSSerializer writer = impl.createLSSerializer();
writer.getDomConfig().setParameter("format-pretty-print",
Boolean.TRUE);
writer.getDomConfig().setParameter("xml-declaration", true);
return writer.writeToString(document);
} catch (Exception e)
{
e.printStackTrace();
return input;
}
}