Java中的XML空格格式

时间:2017-02-17 10:00:07

标签: java xml dom xml-parsing transformer

我在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(&#34; {http://xml.apache.org/xslt} indent-amount&#34;,&#34; 4&#34;);

我明白了:

 <?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>

1 个答案:

答案 0 :(得分:1)

试试这个。

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)