How do I write a DOM Document to File? - java

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!

Related

Storing the contents in a String variable rather than a file

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

Using stream to avoid temp file

I'm trying to create a PDF document with Apache Library FOP. It works well but I have to create a temp file to store an intermediate file (test.fop).
Here is my function:
#RequestMapping(value = "/pdf")
public void showPdfReport(OutputStream pdfOutStream) throws Exception
{
// Setup
FopFactory fopFactory = FopFactory.newInstance();
TransformerFactory factory = TransformerFactory.newInstance();
// Transformation XML to XML-FO
StreamSource xsltSource = new StreamSource(servletContext.getResourceAsStream("resources/xsl/pdfTemplate.fo"));
Transformer transformer = factory.newTransformer(xsltSource);
OutputStream fopOutStream = new BufferedOutputStream(new FileOutputStream(new File(
"C:/Temp/tests/test.fop")));
StreamSource xmlSource = new StreamSource(servletContext.getResourceAsStream("resources/xsl/test.xml"));
StreamResult fopResult = new StreamResult(fopOutStream);
transformer.transform(xmlSource, fopResult);
// Transformation XSL-FO to PDF
Source fopSrc = new StreamSource(new File("C:/Temp/tests/test.fop"));
Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, pdfOutStream);
Result res = new SAXResult(fop.getDefaultHandler());
transformer = factory.newTransformer();
transformer.transform(fopSrc, res);
}
Is it possible to store test.fop in a stream or any buffer instead of a file?
There's an example on the FOP website that explains exactly this. The SAX events emitted from the XSLT transformation are directly fed into FOP. No buffering in a file or in memory.
Sure, you can pass any Reader or InputStream to the StreamSource constructor
You could use StringReader or ByteArrayInputStream for example.

how to append tags in xml in android? and how save that xml file?

i would like to append a new tag with some attributes with those values in to xml file and save that xml file through my application.i have written a method for append a new tag as child to xml file which is available in sdcard of android emulator.the following method for append a new tag as follows
public void appendTag(){
try{
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse (new File("/sdcard/sample.xml"));
Node node = doc.getElementsByTagName("earth").item(0);
//append a new node to earth
Element newelmnt = doc.createElement("new");
newelmnt.appendChild(doc.createTextNode("this is a text"));
node.appendChild(newelmnt);
}
catch (Exception e) {
e.printStackTrace();
}
}
after execution of this method i can't able to find a new tag in xml file.
could please any one help on how to append new tag as child in xml file and how save the modification?
if i uses TransformerFactory i am getting error as
ERROR/AndroidRuntime(13479): java.lang.VerifyError: com.sample.xmlapp.DOMClass
i have used as follows
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("/sdcard/sample.xml"));
transformer.transform(source, result);
Your in memory document will be changed, but you will need to write it to a file again.
Try adding this for writing the document to the file again:
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("/sdcard/sample.xml"));
transformer.transform(source, result);

How to write contents of Document Object to String in NekoHTML?

I am using NekoHTML to parse contents of some HTML file..
Everything goes okay except for extracting the contents of the Document Object to some string.
I've tried uses
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(writer);
transformer.transform(source, result);
But nothing appears returned.
The problem where in Oracle App server 10.3.1.4 http://m-hewedy.blogspot.com/2011/04/oracle-application-server-overrides.html
Posible solution:
//this nekohtml
DOMParser parser = new DOMParser();
parser.parse(archivo);
//this xerces
OutputFormat format = new OutputFormat(parser.getDocument());
format.setIndenting(true);
//print xml for console
//XMLSerializer serializer = new XMLSerializer(System.out, format);
//save xml in string var
OutputStream outputStream = new ByteArrayOutputStream();
XMLSerializer serializer = new XMLSerializer(outputStream, format);
//process
serializer.serialize(parser.getDocument());
String xmlText = outputStream.toString();
System.out.println(xmlText);
//to generate a file output use fileoutputstream instead of system.out
//XMLSerializer serializer = new XMLSerializer(new FileOutputStream(new File("book.xml")), format);
Url: http://totheriver.com/learn/xml/xmltutorial.html#6.2
See e) Serialize DOM to FileOutputStream to generate the xml file "book.xml" .

How to 'transform' a String object (containing XML) to an element on an existing JSP page

Currently, I have a String object that contains XML elements:
String carsInGarage = garage.getCars();
I now want to pass this String as an input/stream source (or some kind of source), but am unsure which one to choose and how to implement it.
Most of the solutions I have looked at import the package: javax.xml.transform and accept a XML file (stylerXML.xml) and output to a HTML file (outputFile.html) (See code below).
try
{
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer(new StreamSource("styler.xsl"));
transformer.transform(new StreamSource("stylerXML.xml"), new StreamResult(new FileOutputStream("outputFile.html")));
}
catch (Exception e)
{
e.printStackTrace();
}
I want to accept a String object and output (using XSL) to a element within an existing JSP page. I just don't know how to implement this, even having looked at the code above.
Can someone please advise/assist. I have searched high and low for a solution, but I just can't pull anything out.
Use a StringReader and a StringWriter:
try {
StringReader reader = new StringReader("<xml>blabla</xml>");
StringWriter writer = new StringWriter();
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer(
new javax.xml.transform.stream.StreamSource("styler.xsl"));
transformer.transform(
new javax.xml.transform.stream.StreamSource(reader),
new javax.xml.transform.stream.StreamResult(writer));
String result = writer.toString();
} catch (Exception e) {
e.printStackTrace();
}
If at some point you want the source to contain more than just a single string, or you don't want to generate the XML wrapper element manually, create a DOM document that contains your source and pass it to the transformer using a DOMSource.
This worked for me.
String str = "<my>xml</my>"
StreamSource src = new StreamSource(new StringReader(str));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Result res = new StreamResult(baos);
transformer.transform(src, res);

Categories