1

我想创建一个带有换行符的 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”、“yes”和缩进量->“4”。但一切都没有改变。无论我是在记事本++ 中打开文件还是作为网页打开文件都没有关系。

4

0 回答 0