Java: How to Indent Xml Generated by Transformer

Java: How to Indent XML Generated by Transformer

You need to enable 'INDENT' and set the indent amount for the transformer:

t.setOutputProperty(OutputKeys.INDENT, "yes");
t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

Update:


Reference : How to strip whitespace-only text nodes from a DOM before serialization?

(Many thanks to all members especially @marc-novakowski, @james-murty and @saad):

Indent XML made with Transformer

Try to set indent-amount, AFAIK the default is 0.

trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4")

indent XML text with Transformer

You may have to specify the amount of spaces to indent as well:

transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

Java XML Output - proper indenting for child items

If the Transformer implementation you're using is Xalan-J, then you should be able to use:

transformer.setOutputProperty(
"{http://xml.apache.org/xslt}indent-amount", "5");

See also: http://xml.apache.org/xalan-j/usagepatterns.html

Java Transformer setOutputProperty()

You are overriding default property indent-amount which is defined in org.apache.xml.serializer package. This enables indentation (since default is 0).

Output properties for XML, HTML, and text transformation output are defined in property files in the org.apache.xml.serializer
package.

You can override the default value of these properties in your
stylesheet by using the attributes of an xsl:output element. You can
override the Xalan specific default settings as follows:

Declare the xalan namespace in your stylesheet element
(xmlns:xalan="http://xml.apache.org/xalan").

Use the namespace prefix you assign (for example, "xalan") to redefine
properties of interest in the stylesheet xsl:output element (for
example, xalan:indent-amount="5"). The following stylesheet fragment
declares the xalan namespace and sets indent-amount to 2:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xalan="http://xml.apache.org/xalan">

<xsl:output method="xml"
encoding="UTF-8"
indent="yes"
xalan:indent-amount="2"/>

You can find more at http://xml.apache.org/xalan-j/usagepatterns.html under chapter Configuring serialization output properties.

All this assuming your serializer is xalan specific

Since moving to java 1.7 Xml Document Element does not indent

Ok ,

I found in Java API this :

If the doctype-system property is specified, the xml output method should output a document type declaration immediately before the first element.

SO I used this property

 transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "yes");

and it solve my problem with out changed my xml declartion.

Thanks.

Indentation Incorrect in XML file created

I can't figure out why the indentation isn't working properly, but I do have a work-around: perform the indentation only after the loop completes. It doesn't make sense anyway to change the indentation each time when you're just going to add elements again.

I've added an extra method prettyPrint() whose only purpose is to beautify the final XML.

public class CreateXmlDemo {

private static String fileLocation = null;
public static void main(String[] args) {
fileLocation = "D:\\Faiz\\output.xml";
CreateXmlDemo c1 = new CreateXmlDemo();
c1.createXmlFile();

CreateXmlDemo c2 = new CreateXmlDemo();
CreateXmlDemo c3 = new CreateXmlDemo();
CreateXmlDemo c4 = new CreateXmlDemo();

CreateXmlDemo[] items= {c2,c3,c4};
for(CreateXmlDemo item : items){
item.writeXml();
}
c1.prettyPrint();
}

public void createXmlFile(){
try{
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("ITEMS");
doc.appendChild(rootElement);
writeWithoutIndentation(doc);
}catch(Exception e){
e.printStackTrace();
}
}

public void writeXml(){

try{
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(fileLocation);
doc.normalize();
Element rootElement = doc.getDocumentElement();
Element item = doc.createElement("ITEM");
Element id = doc.createElement("ID");
id.appendChild(doc.createTextNode("1"));
item.appendChild(id);

Element name = doc.createElement("Name");
name.appendChild(doc.createTextNode("James"));
item.appendChild(name);

rootElement.appendChild(item);
rootElement.normalize();
writeWithoutIndentation(doc);
}catch(Exception e){
e.printStackTrace();
}
}

public void writeWithoutIndentation(Document doc){
try{
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(fileLocation));
transformer.transform(source, result);
}catch(Exception e){
e.printStackTrace();
}
}

public void prettyPrint(){
try{
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(fileLocation);
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(fileLocation));

transformer.transform(source, result);
}
catch(Exception e){
e.printStackTrace();
}
}
}


Related Topics



Leave a reply



Submit