上周我发现了这个有趣的问题。运行下面的程序。很简单,先创建一个dummy xml文件,用标准lib读取,再写回文件。
查看生成的 gtest2.xml,您会看到它有一些不知从何而来的内容。
就我而言,这是错误部分的示例(不同机器上的位置不同)。
<test>1924</test>
<test>1925</test>
<test>t>24</test>
<test>1927</test>
<test>1928</test>
<test>1929</test>
如果我将 xml 版本更改为 1.0,则不会发生这种情况。那么我的代码或jdk有问题吗?
这是测试代码:
import java.io.File;
import java.io.PrintWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
public class DocumentBuilderCheck {
public static void main(String[] args) throws Exception {
String filename = "/tmp/gtest.xml";
generateXmlFile(filename, 2500);
Document doc = readXmlFile(filename);
String filename2 = "/tmp/gtest2.xml";
writeDocument(doc, filename2);
}
private static void writeDocument(Document document, String filename) throws Exception {
StreamResult streamResult = new StreamResult(filename);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.transform(new DOMSource(document), streamResult);
}
private static Document readXmlFile(String filename) throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new File(filename));
return doc;
}
private static void generateXmlFile(String filename, int total)
throws Exception {
File f = new File(filename);
PrintWriter pw = new PrintWriter(f);
pw.write("<?xml version=\"1.1\" encoding=\"UTF-8\"?>");
pw.write("<main_tag>");
for (int i = 0; i < total; i++) {
pw.write("<test>" + String.format("%04d", i) + "</test>");
}
pw.write("</main_tag>");
pw.close();
}
}