gpt4 book ai didi

java - Java 中的 XML 空格格式

转载 作者:行者123 更新时间:2023-11-30 06:53:22 24 4
gpt4 key购买 nike

我在 Java 中格式化空白时遇到问题。我向文件添加了新属性,但格式不正确。

    Attr attr = doc.createAttribute("name");
attr.setValue("name");
element.setAttributeNode(attr);
element.setTextContent("Something=" + this.thumbnailCacheSize);

NodeList items = doc.getElementsByTagName("mbean");
Node e = items.item(0);
e.appendChild(element);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT,"yes");
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(filepath);

transformer.transform(source,result);

它应该看起来像这样:

 <?xml version="1.0" encoding="UTF-8" standalone="no"?>
<server>
<mbean code="code" name="name">
<attribute name="name3">Something3=500</attribute>
<attribute name="name2">Something2=500</attribute>
<attribute name="name1">Something1=500</attribute>
<attribute name="name">Something=500</attribute>
</mbean>
</server>

但是就像:

 <?xml version="1.0" encoding="UTF-8" standalone="no"?>
<server>
<mbean code="code" name="name">
<attribute name="name3">Something3=500</attribute>
<attribute name="name2">Something2=500</attribute>
<attribute name="name1">Something1=500</attribute>
<attribute name="name">Something=500</attribute>
</mbean>
</server>

当我使用时: Transformer.setOutputProperty("{ http://xml.apache.org/xslt }缩进量", "4");

我得到:

 <?xml version="1.0" encoding="UTF-8" standalone="no"?>
<server>
<mbean code="code" name="name">
<attribute name="name3">Something3=500</attribute>
<attribute name="name2">Something2=500</attribute>
<attribute name="name1">Something1=500</attribute>
<attribute name="name">Something=500</attribute>
</mbean>
</server>

最佳答案

试试这个。

Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // enable indent
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); // 4 is indent space (default is zero)

关于java - Java 中的 XML 空格格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42294870/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com