我想创建一个带换行符的xml文件,看起来有点像这样:
<Instrument currencyId="THB"
disabledCount="0"
hasBeenEnabledOnce="TRUE"
</Instrument>
使用这段代码我接近了,但所有属性似乎都在同一行上结束了:
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("Instrument");
doc.appendChild(rootElement);
Instrument.setAttribute("currencyId", "THB");
Instrument.setAttribute("disabledCount", "0");
Instrument.setAttribute("hasBeenEnabledOnce", "TRUE");
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("C:\\file.xml"));
transformer.transform(source, result);
我得到以下结果:
<Instrument currencyId="THB" disabledCount="0" hasBeenEnabledOnce="TRUE"
如何在属性之间添加换行符?
只是略微注意,我认为transformer.setOutputProperies可以解决问题,通过搜索类似的问题我最终得到“OutputKeys.INDENT”,“是”和缩进量 - &gt; “4”。但没有任何改变。 无论我是用notepad ++还是网页打开文件。