Я не знаю, какие библиотеки XML вы используете.Я только что попробовал с сырой установкой и прекрасно работает для меня.
import java.io.StringReader;
import java.io.StringWriter;
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;
//from w w w. ja va2 s.c om
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
public class Transform {
public static void main(String[] args) throws Exception {
String unformattedXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<note>\n"
+ " <to>example</to>\n"
+ " <from>Server</from>\n"
+ " <heading>Reminder</heading>\n"
+ " <body></body>\n"
+ "</note>";
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty("http://www.oracle.com/xml/is-standalone", "yes");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "yes");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
StringWriter stringWriter = new StringWriter();
transformer.transform(new DOMSource(convertStringToDocument(unformattedXml).getDocumentElement()), new StreamResult(stringWriter));
String s = stringWriter.toString();
System.out.println(s);
}
private static Document convertStringToDocument(String xmlStr) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try {
builder = factory.newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(xmlStr)));
return doc;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
Вывод:
<?xml version="1.0" encoding="UTF-8"?>
<note>
<to>example</to>
<from>Server</from>
<heading>Reminder</heading>
<body/>
</note>