making indented XML

S

Steve Maring

I could swear that this used to work for me, but when I run the
following code I get:

<?xml version="1.0" encoding="UTF-8"?>
<a><b><c/></b></a>

which is not the:

<a>
<b>
<c/>
</b>
</a>

that I want and was expecting. I'm running JDK 1.4.2_03 on W2K with
the latest Xalan and Xerces.

I've tried running it like the following:

java -classpath .;xercesImpl.jar;xalan.jar;xml-apis.jar PrintTest
java -Djava.endorsed.dirs=. -classpath
..;xercesImpl.jar;xalan.jar;xml-apis.jar PrintTest
java -Xbootclasspath/p:xercesImpl.jar;xalan.jar;xml-apis.jar
-classpath .;xercesImpl.jar;xalan.jar;xml-apis.jar PrintTest

I'm at a loss here. Can somebody throw me a bone?


Cheers.
Steve Maring
steve at maring dot org



import java.io.StringReader;
import java.io.PrintWriter;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.OutputKeys;

import org.w3c.dom.Document;
import org.xml.sax.InputSource;


public class PrintTest
{
public static void main( String[] args )
{
try
{
String xml = "<a><b><c></c></b></a>";
PrintWriter printWriter = new PrintWriter( System.out, true
);
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(
new InputSource( new StringReader( xml ) ) );
TransformerFactory transFactory =
TransformerFactory.newInstance();
Transformer transformer = transFactory.newTransformer();
transformer.setOutputProperty( OutputKeys.METHOD, "xml" );
transformer.setOutputProperty( OutputKeys.INDENT, "true" );
transformer.setOutputProperty(
OutputKeys.OMIT_XML_DECLARATION, "true" );
transformer.setOutputProperty(
"{http://xml.apache.org/xslt}indent-amount", "4" );
transformer.transform(
new DOMSource( doc ), new StreamResult( printWriter ) );
}
catch ( Exception e )
{
e.printStackTrace();
}
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top