Java: Saving StreamResult to a file - java

I am doing some data conversion(like csv) to xml with SAX then using transformer in Java. The result is in StreamResult, and I am trying to save this result to a file.xml but I can't find way to save StreamResult into file. am I doing this all wrong?

Your StreamResult should be created on the basis of a file, e.g.
StreamResult sr = new StreamResult(new File("/my/file.xml"));
If you give your Transformer such a StreamResult, it will write its result directly into the file you specified.

I am not familiar with the API... but does this link give you what you are after?
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
//initialize StreamResult with File object to save to file
StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
String xmlString = result.getWriter().toString();
System.out.println(xmlString);

Related

How to print xml file colored in console using java

I'm trying to print an XML file colored on console using java, but I have never done this before, and I have no idea how to do that.
This code prints an XML file on console.
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder1;
builder1 = factory.newDocumentBuilder();
Document document;
document = builder1.parse(new File(pathFilename));
TransformerFactory tFactory = TransformerFactory.newInstance();
tFactory.setAttribute("indent-number", new Integer(2));
Transformer transformer = tFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
DOMSource source = new DOMSource(document);
StreamResult result2 = new StreamResult(System.out);
transformer.transform(source, result2);
I would like to print it on console like an editor, for example Notepad++.
Any suggests how to do it?
An example of output on console:
<ControllerMode dataItemId="mode" sequence="286201" timestamp="2019-06-27T11:23:02.641182Z">AUTOMATIC</ControllerMode>

dom4j - xpath - get xml as string for Document.valueOf

Is there a way to write XPath expression that will be returning xml tree as string when called with Document.valueOf method from dom4j library? I tried /node(), but it returns just texts in all nodes, not including tags.
Method 1 :
String result = document.toXML().toString();
Method 2 : (a more elegant aproach)
DOMSource domSource = new DOMSource(document);
StringWriter writer = new StringWriter();
StreamResult streamResult = new StreamResult(writer);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory .newTransformer();
transformer.transform(domSource, streamResult);
String result = writer.toString();

How to create line breaks in xml using java

I want to create an xml file with line breaks, looking somewhat like this:
<Instrument currencyId="THB"
disabledCount="0"
hasBeenEnabledOnce="TRUE"
</Instrument>
Using this code I got close but all attributes seems to be end up on the same row:
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("Instrument");
doc.appendChild(rootElement);
Instrument.setAttribute("currencyId", "THB");
Instrument.setAttribute("disabledCount", "0");
Instrument.setAttribute("hasBeenEnabledOnce", "TRUE");
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("C:\\file.xml"));
transformer.transform(source, result);
I get the following result:
<Instrument currencyId="THB" disabledCount="0" hasBeenEnabledOnce="TRUE"
How can I add linebreaks between the attributes??
just a slight notice, I thought that transformer.setOutputProperies could solve the problem, by searching for similar problems I ended up with "OutputKeys.INDENT", "yes", and the indent-amount -> "4". But nothing's changed.
Doesnt matter if I open the file in notepad++ or as a webpage.

XML file saved from Swing application

I'm developing a Java Swing Application, and I want to create objects and save them in a XML file, with the information that a user writes in some text fields.
How can I save that data into a XML file, to form those objects?
You can write your own XML-Writer to write out objects/text to a XML file. For example using DOM
public boolean writeCommonSettingsFromGUI()
{
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("NAME_OF_A_ELEMENT");
doc.appendChild(rootElement);
Element xmlInfo = doc.createElement("NAME_OF_ANOTHER_ELEMENT");
xmlInfo.setTextContent("YOUR_CONTENT_TO_SET_FOR_THIS_ELEMENT");
rootElement.appendChild(xmlInfo);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputPropertiesFactory.S_KEY_INDENT_AMOUNT, "5");
transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
DOMSource source = new DOMSource(doc);
StreamResult result = null;
result = new StreamResult(new File("FILE_PATH_WHERE_TO_SAVE_YOUR_XML"));
transformer.transform(source, result);
return true;
}
use castor framework, you can map your java class to xml file and vice versa

Java XML Output - proper indenting for child items

I'd like to serialize some simple data model into xml, I've been using the standard java.org.w3c -related code (see below), the indentation is better than no "OutputKeys.INDENT", yet there is one little thing that remains - proper indentation for child elements.
I know that this has been asked before on stackoverflow , yet that configuration did not work for me, this is the code I'm using :
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.newDocument();
doc = addItemsToDocument(doc);
// The addItemsToDocument method adds childElements to the document.
TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setAttribute("indent-number", new Integer(4));
// switching to setAttribute("indent-number", 4); doesn't help
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(outFile);
// outFile is a regular File outFile = new File("some/path/foo.xml");
transformer.transform(source, result);
The output produced is :
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<stuffcontainer>
<stuff description="something" duration="240" title="abc">
<otherstuff />
</stuff>
</stuffcontainer>
Whereas I would want it (for more clarity) like :
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<stuffcontainer>
<stuff description="something" duration="240" title="abc">
<otherstuff />
</stuff>
</stuffcontainer>
I was just wondering if there is a way of doing this, make it properly indented for the child elements.
Thank you in advance !
Happy Easter coding :-) !
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
import com.sun.org.apache.xml.internal.serializer.OutputPropertiesFactory
transformer.setOutputProperty(OutputPropertiesFactory.S_KEY_INDENT_AMOUNT, "4");
Document doc;
.....
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
transformer.transform(new DOMSource(doc), new StreamResult(new File("filename.xml")));
transformer.transform(new DOMSource(doc), new StreamResult(System.out));

Categories

Resources