问题
I already looked through the postings on stackoverflow but it seems that nothing helps.
Here is what have:
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setAttribute("indent-number", 2);
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(xmlDoc);
StreamResult result = new StreamResult(new File("C:\\testing.xml"));
transformer.transform(source, result);
and this is what I get as output:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Satellite SatelliteName="" XmlFileVersion="">
<test0>
<test1>
<test2>
<test3>
<test4>
<test5>
<test6>
<test7>
<test8>
<test9/>
</test8>
</test7>
</test6>
</test5>
</test4>
</test3>
</test2>
</test1>
</test0>
</Satellite>
No tabs or no spaces.
I set the indent-number because of a possible bug of java and I activated OutputKeys.INDENT.
Any other ideas?
Edit 1 (after adarshr's fix):
I now have white spaces. Only the first Satellite Entry is placed in the first line which shouldn't be.
<?xml version="1.0" encoding="UTF-8"?><Satellite SatelliteName="" XmlFileVersion="">
<test0>
<test1>
<test2>
<test3>
<test4>
<test5>
<test6>
<test7>
<test8>
<test9>blah</test9>
</test8>
</test7>
</test6>
</test5>
</test4>
</test3>
</test2>
</test1>
</test0>
<sdjklhewlkr/>
</Satellite>
Edit 2:
So the current state is that I now have whitespaces but I have no line feed after the XML declaration. How can I fix this?
回答1:
try setting the indent amount like this:
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
回答2:
I've played with Transformer, but never got it to work. I used the Xerces (Apache) library, which has always worked like a charm for me. Try something like
OutputFormat format = new OutputFormat(document);
format.setLineWidth(65);
format.setIndenting(true);
format.setIndent(2);
Writer outxml = new FileWriter(new File("out.xml"));
XMLSerializer serializer = new XMLSerializer(outxml, format);
serializer.serialize(document);
回答3:
I had faced the same problem sometime back. The issue was that the implementation of the TransformerFactory or Transformer classes loaded was different from what Java intends it to be.
There was also a System property that we had to set in order to solve it. I will try and get that for you in a moment.
EDIT: Try this
System.setProperty("javax.xml.transform.TransformerFactory", "org.apache.xalan.xsltc.trax.TransformerFactoryImpl");
回答4:
I can give you 2 advice
1st You can use xsl file for pretty output
2nd I found interesting library ode-utils-XXX.jar
And you can just write like
String result = "";
try {
result = DOMUtils.prettyPrint(doc);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(result);
来源:https://stackoverflow.com/questions/5142632/java-dom-xml-file-create-have-no-tabs-or-whitespaces-in-output-file