JAVA 8 xml pretty output not working properly - java

I try to save Document to the XML in pretty output. But problem is every new element start from line of pervious element end tag.
Example:
<?xml version="1.0" encoding="UTF-8"?><report>
<jiraentry category="SERVICE & ASSET" component="DOCMAN" priority="10" summary="Bug Generated By, UNCHECKED_ACCESS">Tool:UNCHECKED_ACCESS Date:2015-11-12
</jiraentry>
You can see that and text in print in pervious line.Here is the below my Java code which i used to save xml by using transformer.
//normalize the xml file
root.getDocumentElement().normalize();
//remove standalone no
root.setXmlStandalone(true);
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setAttribute("indent-number", new Integer(0));//add intend to the new line
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(root);
StreamResult result = new StreamResult(new OutputStreamWriter(new FileOutputStream(this.outpath), "UTF-8"));//save the file
transformer.transform(source, result);
Any one can suggest me to make this more pretty and clear.

You need to set the indent amount for the transformer as shown in the snippet below:
t.setOutputProperty(OutputKeys.INDENT, "yes");
t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
Useful Reference: Similar Question

Related

Save API Response as XML file

I'm actually working on a test project using "REST Assured" in Java :Using a get API to retrive an xml content ( the content type is "application/atom+xml") then update this xml and push it using a post API.
My idea is to save the response body of get API in xml file -> update it -> post it -> delete the xml file
and I'm blocked in the first step to save the response in xml file, I tried many methods but could'nt succeed.
Any solution for this or any other ideas
I tried saving the response as a String then convert it to XML , but the xml content is too big so I get many errors which fixing it will change the format/content
I also tried using the XMLpath to parse the content that I want to change without saving it to a file but couldnt make it work because I save the response to a string then parse it
The issue was with the xml format , I had to use transformer to make it pretty and safe it as xml
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes" );
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
Writer out = new StringWriter();
transformer.transform(new DOMSource(document), new StreamResult(out));
FileWriter fw = new FileWriter("my-file.xml");
fw.write( out.toString());
fw.close();

Disable Indent in JAXP when transform XML

I am using JAXP to convert DOM tree to XML. I do not want any intends in my result XML.
This is my code:
root.normalize();
DOMSource domSource = new DOMSource(root);
StreamResult result = new StreamResult(outputStream);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
transformer.setOutputProperty(OutputKeys.INDENT, "no");
transformer.transform(domSource, result);
It works nice if source is not intended and result is also not intended,
If the source XML file is pretty formatted, then "INDENT = no" takes no effect.
The transformed XML file is still indented but I do not want that.
This input generate correct output with no intends.:
<InitMessage xmlns="http://www.test.com/"><operation>while</operation><part1>6</part1><part2>2</part2><part3>5</part3><part4>1</part4></InitMessage>
But this one no and I still got pretty printed intended xml in my output (one line).
<InitMessage xmlns="http://www.test.com/">
<operation>while</operation>
<part1>6</part1>
<part2>2</part2>
<part3>5</part3>
<part4>1</part4>
</InitMessage>
Setting INDENT to no only indicates that the processor is not allowed to add
additional whitespace, not that it will strip existing whitespace.

Java XML dom: prevent collapsing empty element

I use the javax.xml.parsers.DocumentBuilder, and want to write a org.w3c.dom.Document to a file.
If there is an empty element, the default output is a collapsed:
<element/>
Can I change this behavior so that is doesn't collapse the element? I.e.:
<element></element>
Thanks for your help.
This actualy depends on the way how you're writing a document to a file and has nothing to do with DOM itself. The following example uses popular Transformer-based approach:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
Document document = factory.newDocumentBuilder().newDocument();
Element element = document.createElement("tag");
document.appendChild(element);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "html");
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);
It outputs <tag></tag> as you're expecting. Please note, that changing the output method has other side effects, like missing XML declaration.

Header Tag in XML using JAXB

Right now I am getting this as an XML output from my JAXB Marshaller
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><create></create>
But I want my root element as:
<create xmlns="http://ws.abc.com" xmlns:doc="http://ws.abc.com">
Do I need to modify this using parsers, Or is there any annotation available.
You can set the following property on the Marshaller to remove the header:
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
For More Information
http://blog.bdoughan.com/2011/08/jaxb-and-java-io-files-streams-readers.html
I've used a Transformer in the past. You'd want something like the following sample code:
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
StreamResult transformedDoc = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(content); // Where content is a org.w3c.dom.Document object.
transformer.transform(source, transformedDoc);
So maybe do your marshalling and then process. Not sure if this is the best approach but it would work.

GAE Servlet XML Response. How?

I need to send XML response from my GAE servlet.
What I already have is:
- An instance of org.w3c.dom.Document populated with data
- HttpServletResponse (that gives me either a PrintWriter or a ServletOutputStream)
If XMLSerializer were whitelisted in GAE, I could finish the work. ..but it's not.
My question is: How to cook the food from these ingredients?
(without 3rd party libraries please)
Thanks for any hints.
Have you tried:
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, ENCODING);
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", INDENT);
StreamResult result = new StreamResult(writer);
DOMSource source = new DOMSource(document);
transformer.transform(source, result);

Categories