I'm using Transformer to prettify and to insert indentation to an XML which is originally one big line.
Here is my code:
BufferedWriter br = null;
Source xmlInput = new StreamSource(inputSR);
StringWriter stringWriter = new StringWriter();
StreamResult xmlOutput = new StreamResult(stringWriter);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setAttribute("indent-number", 2);
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.transform(xmlInput, xmlOutput);
How can I write the xmlOutput to a file, line by line (without loading the whole string to the memory)?
Instead of a StringWriter, use a FileOutputStream:
StreamResult xmlOutput = new StreamResult(new FileOutputStream("output.xml"))
This will write incrementally to the file. It won't necessarily write line-by-line (lines don't mean much in XML), but I can't see why you would want that.
Related
How do I write this document to the local filesystem?
public void docToFile(org.w3c.dom.Document document, URI path) throws Exception {
File file = new File(path);
}
I need to iterate the document, or might there be a "to xml/html/string" method? I was looking at:
document.getXmlEncoding();
Not quite what I'm after -- but something like that. Looking for the String representation and then to write that to file like:
Path file = ...;
byte[] buf = ...;
Files.write(file, buf);
https://docs.oracle.com/javase/tutorial/essential/io/file.html
I would use a transformer class to convert the DOM content to an xml file, something like below:
Document doc =...
// write the content into xml file
DOMSource source = new DOMSource(doc);
FileWriter writer = new FileWriter(new File("/tmp/output.xml"));
StreamResult result = new StreamResult(writer);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.transform(source, result);
I hope this ends up working for you!
I seek your help, I have an automatically generated XML File that I need to validate against a DTD, so I have to modify the generated XML to add the doctype tag isn't added when I use the following code, I have consulted many threads but no positive result.
Here is the concerned part in my code:
InputStream inputStream= new FileInputStream(extractedFileURL);
Reader reader = new InputStreamReader(inputStream,"UTF-8");
InputSource is = new InputSource(reader);
is.setEncoding("UTF-8");
Document doc = docBuilder.parse(is);
///Add Doctype declaration to the extracted XML File
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
org.w3c.dom.DOMImplementation domImpl = doc.getImplementation();
DocumentType doctype = domImpl.createDocumentType("doctype",
"SYSTEM"
,
"registry\\ixb\\dtds\\extractor.dtd\\generatedDTD1.dtd");
//transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, doctype.getPublicId());
transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, doctype.getSystemId());
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(extractedFileURL));
transformer.transform(source, result);
I have a process of XML transform in which I am writing the output transformed XML to a file. But instead of storing it in a file I want to store it in a string variable. I have created a string variable, please advise how can I store the generated XML in a string variable (msgxml instead of writing a file).
String msgxml;
System.setProperty("javax.xml.transform.TransformerFactory",
"org.apache.xalan.processor.TransformerFactoryImpl");
FileInputStream xml = new FileInputStream(xmlInput);
FileInputStream xsl = new FileInputStream(xslInput);
FileOutputStream os = new FileOutputStream(outputXmlFile);
TransformerFactory tFactory = TransformerFactory.newInstance();
// Use the TransformerFactory to process the stylesheet source and produce a Transformer
StreamSource styleSource = new StreamSource(xsl);
Transformer transformer = tFactory.newTransformer(styleSource);
StreamSource xmlSource = new StreamSource(xml);
StreamResult result = new StreamResult(os);
//here we are storing it in a file ,
try {
transformer.transform(xmlSource, result);
} catch (TransformerException e) {
e.printStackTrace();
}
One way is to use an ByteArrayOutputStream instead of a FileOutputStream:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
TransformerFactory tFactory = TransformerFactory.newInstance();
...
StreamSource xmlSource = new StreamSource(xml);
StreamResult result = new StreamResult(baos); // write to the byte array stream
//here we are storing it in a file ,
try {
transformer.transform(xmlSource, result);
}
...
msgxml = baos.toString("UTF-8"); // get contents of stream using UTF-8 encoding
Another solution is to use a java.io.StringWriter:
StringWriter stringWriter = new StringWriter();
StreamResult result = new StreamResult(stringWriter);
...
msgxml = stringWriter.toString();
I am editing an XML file in Java with a Transformer by adding more nodes. The old XML code is unchanged but the new XML nodes have < and > instead of <> and are on the same line. How do I get <> instead of < and > and how do I get line breaks after the new nodes. I already read several similar threads but wasn't able to get the right formatting. Here is the relevant portion of the code:
// Read the XML file
DocumentBuilderFactory dbf= DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc=db.parse(xmlFile.getAbsoluteFile());
Element root = doc.getDocumentElement();
// create a new node
Element newNode = doc.createElement("Item");
// add it to the root node
root.appendChild(newNode);
// create a new attribute
Attr attribute = doc.createAttribute("Name");
// assign the attribute a value
attribute.setValue("Test...");
// add the attribute to the new node
newNode.setAttributeNode(attribute);
// transform the XML
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
StreamResult result = new StreamResult(new FileWriter(xmlFile.getAbsoluteFile()));
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
Thanks
To replace the > and other tags you can use org.apache.commons.lang3:
StringEscapeUtils.unescapeXml(resp.toString());
After that you can use the following property of transformer for having line breaks in your xml:
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
based on a question posted here:
public void writeToOutputStream(Document fDoc, OutputStream out) throws Exception {
fDoc.setXmlStandalone(true);
DOMSource docSource = new DOMSource(fDoc);
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.INDENT, "no");
transformer.transform(docSource, new StreamResult(out));
}
produces:
<?xml version="1.0" encoding="UTF-8"?>
The differences I see:
fDoc.setXmlStandalone(true);
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
Try passing InputStream instead of Writer to StreamResult.
StreamResult result = new StreamResult(new FileInputStream(xmlFile.getAbsoluteFile()));
The Transformer documentation also suggests that.
This question already has answers here:
Pretty-printing output from javax.xml.transform.Transformer with only standard java api (Indentation and Doctype positioning)
(4 answers)
Closed 5 years ago.
I am trying to create XML from Java and am having problems with indenting. In the following code you can see OutputKeys.INDENT set to yes...
//set up a transformer
TransformerFactory transfac = TransformerFactory.newInstance();
Transformer trans = transfac.newTransformer();
trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
trans.setOutputProperty(OutputKeys.INDENT, "yes");
//create string from xml tree
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(doc);
trans.transform(source, result);
String xmlString = sw.toString();
//print xml
System.out.println(xmlString);
but it seems to have no affect, the output is:
<dataset id="1"><br>
<path></path><br>
<session id="1"><br>
<method><br>
<timestamp>a timestamp</timestamp><br>
<signiture><br>
<classPath></classPath><br>
<name>methodName</name><br>
<declarationType>String</declarationType><br>
<parameters><br>
<parameter>String</parameter><br>
<parameter>int</parameter><br>
</parameters><br>
</signiture><br>
<arguments><br>
<argument>SomeValue</argument><br>
<argument>AnotherValue</argument><br>
</arguments><br>
<return>ReturnValue</return><br>
</method><br>
</session><br>
</dataset><br>
Try to set indent-amount, AFAIK the default is 0.
trans.setOutputProperty("{http://xml.apache.org/xslt}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));