Save API Response as XML file - java

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();

Related

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 8 xml pretty output not working properly

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

Error writing XML Document to file in Java

I am trying to write org.w3c.dom.Document to a file. I get the Document from
String URL = "http://...."
DOMParser parser = new DOMParser();
Document doc = null;
try {
parser.parse(new InputSource(URL));
doc = parser.getDocument();
} catch () {}
Then I write this Document to a file using
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(file));
transformer.transform(source, result);
While doing this I keep getting the following error
ERROR: 'Namespace for prefix 'xlink' has not been declared.'
What might be wrong? Thanks
I recommend using a different library such as Dom4J rather than trying to fight your way through the built-in XML API in Java. Dom4J is better designed and makes your code much more readable:
Document doc = new SAXReader().read(inputStream);
new XMLWriter(outputStream).write(doc);
None of this mucking around with FactoryFactoryFactoryFactories.
I know this doesn't directly answer your question but hopefully it will help anyway. Dom4j knows how to talk to the Java XML API so you can mix and match them to suit your needs. You can even plug it into Xalan or something similar if you want to use XSLT.

How to get a non-XML output using JDOM XSLTransformer?

I have an XML file which I'd like to parse into a non-XML (text) file based on a XLST file. The code in both seem correct, and it works when testing manually, but I'm having a problem doing this programatically.
I'm using JDOM's XSLTransformer class to apply the XSLT to the XML and it returns it in the format of a JDOM Document. The problem here is that I can't seem to access anything in the Document as it is not a proper XML file and I get a "java.lang.IllegalStateException: Root element not set" error.
Is there a better way within Java to obtain a non-XML file as a result of XSLT?
JDOM XSLTTransformer is a convenience wrapper around javax.xml.transform.Transformer for JDOM input and output.
A JDOM input is easily transformed to text output.
Transformer transformer = TransformerFactory.newInstance().newTransformer(new StreamSource(stylesheet));
JDOMSource in = new JDOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult out = new StreamResult(writer);
transformer.transform(in, out);
return writer.toString();

self-closing tags with XMLEventWriter

So the question is pretty much as stated in the title. I am doing some xml work and using XMLEventWriter. The big issue I'm having is that I need to create some self closing tags
The problem is that I haven't figured out a way to do this with the eventWriter. I have tried everything I can think of using XMLEventFactory but nothing seems to work. Any help would be greatly appreciated.
I'm not sure if this is possible using XMLEventWriter. It is certainly possible with XMLStreamWriter.
If you are stuck with XMLEventWriter, you could transform the data afterwards.
Reader xml = new StringReader("<?xml version=\"1.0\"?><foo></foo>");
TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer transformer = transFactory.newTransformer();
transformer.transform(new StreamSource(xml),
new StreamResult(System.out));
The output of the above code is:
<?xml version="1.0" encoding="UTF-8"?><foo/>

Categories