我试图用Java编写使用的DocumentBuilder一个简单的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);
}
}