This is a sample XML that I am using for testing.
<?xml version="1.0" encoding="UTF-8"?>
<sample attr1="v1"
attr2="v2"
attr3="v3">
<content anotherAttr="" />
</sample>
This is the output after a simple read and write
<?xml version="1.0" encoding="UTF-8"?><sample attr1="v1" attr2="v2" attr3="v3">
<content anotherAttr=""/>
</sample>
This is my test code:
public static void main(String[] args) throws Exception {
File fileInput = new File("input.xml");
File fileOutput = new File("output.xml");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setExpandEntityReferences(false);
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.parse(fileInput);
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
DOMSource source = new DOMSource(document);
FileOutputStream fos = new FileOutputStream(fileOutput);
StreamResult result = new StreamResult(fos);
transformer.transform(source, result);
}
Am I doing something wrong?
Thanks,
Alex
Sorry... I forgot the code tags...
This is a sample XML that I am using for testing.
<?xml version="1.0" encoding="UTF-8"?>
<sample attr1="v1"
attr2="v2"
attr3="v3">
<content anotherAttr="" />
</sample>
This is the output after a simple read and write
<?xml version="1.0" encoding="UTF-8"?><sample attr1="v1" attr2="v2" attr3="v3">
<content anotherAttr=""/>
</sample>
This is my test code:
public static void main(String[] args) throws Exception {
File fileInput = new File("input.xml");
File fileOutput = new File("output.xml");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setExpandEntityReferences(false);
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.parse(fileInput);
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
DOMSource source = new DOMSource(document);
FileOutputStream fos = new FileOutputStream(fileOutput);
StreamResult result = new StreamResult(fos);
transformer.transform(source, result);
}
Use JDK 1.4.x for indentation to get added. Setting the indentation adds the newline between the xml declaration and he root element tag. Whitespace between elements is considered to be a text node and is preserved. Whitespace/newline between attributes is not a text node and is not preserved.
The following input.xml would produce the same output as an input.xml without whitespaces and newlines.
<?xml version="1.0" encoding="UTF-8"?>
<sample attr1="v1"
attr2="v2"
attr3="v3">
<content anotherAttr="" />
</sample>