Java DocumentBuilder - XML文件中的错误缩进

时间:2015-07-14 17:27:49

标签: java xml indentation domparser

我尝试使用DocumentBuilder在Java中编写一个简单的XML文件。 我希望XML文件看起来像这样:

<outer>
     <inner>
          <element name="WEB"/>
          <element name="WEB"/>
          <element name="WEB"/>
     </inner>
</outer>

但它会像这样产生它:

<outer>
     <inner>
          <element name="WEB"/>
          <element name="WEB"/>
     <element name="WEB"/>
     </inner>
</outer>

为什么第三个元素与其他两个元素没有相同的缩进? 注意:我再次读取XML文件以模拟项目中的方法,在那里我读取XML文件,添加一个元素并将其保存到XML文件中。 这是我的代码:

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.IOException;

public class main {
    private static String FILEPATH = "/tmp/xmltest.xml";
    private static DocumentBuilderFactory docFactory;
    private static DocumentBuilder docBuilder;
    private static TransformerFactory transformerFactory;
    private static Transformer transformer;

    public static void main(String[] args) throws IOException, SAXException, ParserConfigurationException, TransformerConfigurationException, TransformerException{
        docFactory = DocumentBuilderFactory.newInstance();
        docBuilder = docFactory.newDocumentBuilder();
        transformerFactory= TransformerFactory.newInstance();
        transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "1");

        // Creating the XML file structure
        Document document = docBuilder.newDocument();
        Element rootElement = document.createElement("outer");
        document.appendChild(rootElement);

        Element inner = document.createElement("inner");
        rootElement.appendChild(inner);

        // Write XML file
        write(document);

        // Read XML file
        document = docBuilder.parse(FILEPATH);
        Element root = document.getDocumentElement();
        Element innerElement = (Element)root.getElementsByTagName("inner").item(0);

        // Add element
        Element e = document.createElement("element");
        e.setAttribute("name", "WEB");
        innerElement.appendChild(e);

        // Add element
        e = document.createElement("element");
        e.setAttribute("name", "WEB");
        innerElement.appendChild(e);

        // Write XML file
        write(document);

        // Read XML fil
        document = docBuilder.parse(FILEPATH);
        root = document.getDocumentElement();
        innerElement = (Element)root.getElementsByTagName("inner").item(0);

        // Add element
        e = document.createElement("element");
        e.setAttribute("name", "WEB");
        innerElement.appendChild(e);

        // Write XML file
        write(document);
    }

    private static void write(Document document) throws TransformerException {
        DOMSource source = new DOMSource(document);
        StreamResult result = new StreamResult(new File(FILEPATH));
        transformer.transform(source, result);
    }
}

1 个答案:

答案 0 :(得分:3)

用于indententation的xmlfile中的文本节点被视为数据。因为这个你的缩进是为了折腾。你可以解决这个问题,如下所示:

private static void removeEmptyText(Node node){
    Node child = node.getFirstChild();
    while(child!=null){
        Node sibling = child.getNextSibling();
        if(child.getNodeType()==Node.TEXT_NODE){
            if(child.getTextContent().trim().isEmpty())
                node.removeChild(child);
        }else
            removeEmptyText(child);
        child = sibling;
    }
}

private static void write(Document document) throws TransformerException {
    removeEmptyText(document.getDocumentElement());
    DOMSource source = new DOMSource(document);
    StreamResult result = new StreamResult(new File(FILEPATH));
    transformer.transform(source, result);
}

这里我在写入文件之前从dom中删除所有缩进文本节点。