Java: convert StreamResult to DOM - java

I am performing a xslt transformation from one xml format to another with saxon and xslt, after what transforming the result xml into Java DOM to work with it further:
System.setProperty("javax.xml.transform.TransformerFactory", "net.sf.saxon.TransformerFactoryImpl");
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer(new StreamSource(new File("xslt.xsl")));
transformer.transform(new StreamSource(new File(inputXML)),
new StreamResult(new File (outputXML)));
DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = documentBuilder.parse(outputXML);
What I don't like in this situation, is creating intermediate outputXML file. Is it possible to avoid its creating?

The answer was provided by #Andreas. If someone is interested, the result code snippet in my case looked like this:
System.setProperty("javax.xml.transform.TransformerFactory", "net.sf.saxon.TransformerFactoryImpl");
TransformerFactory tFactory = TransformerFactory.newInstance();
DOMResult xmlResult = new DOMResult();
Transformer transformer = tFactory.newTransformer(new StreamSource(new File("xslt.xsl")));
transformer.transform(new StreamSource(new File(outputXML)),
xmlResult);
Document document = (Document) xmlResult.getNode();

DocumentResult result = new DocumentResult();
transformer.transform( new StreamSource(new File(inputXML)), result );
Document transformedDoc = result.getDocument();

Related

Entity reference is not shown in the XML

I create entity reference with EntityReference ent = doc.createEntityReference(txt). Then I add it to the node: node.appendChild(ent); and the txt is like "lt". So, I expect to see < in my XML file. But all entity references are missing. Other elements are added and shown well, but not EntityReference.
XML is created as:
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
docBuilder = docFactory.newDocumentBuilder();
doc = docBuilder.newDocument();
dumping to the file:
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new StringWriter());
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.transform(source, result);
String xmlString = result.getWriter().toString();
return xmlString;
The result XML has a standard header:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
...
Where can be a problem?

Large XSLT (~10000 lines) failed to transform input message (Xalan)

I am facing a classic problem, I have an XSLT with ~10000 lines and trying to use Java for transformation
TransformerFactory factory = TransformerFactory.newInstance();
Source xslt = new StreamSource(new File("convertor.xslt"));
Transformer transformer = factory.newTransformer(xslt);
Source text = new StreamSource(new File("input.xml"));
transformer.transform(text, new StreamResult(new File("output.xml")));
But unfortunately ended up with below error:
com.sun.org.apache.bcel.internal.generic.ClassGenException: Not targeting 45269: nop[0](1), but null
at java.xml/com.sun.org.apache.bcel.internal.generic.BranchInstruction.updateTarget(BranchInstruction.java:217)
at java.xml/com.sun.org.apache.xalan.internal.xsltc.compiler.util.MethodGenerator.outline(MethodGenerator.java:1721)
at java.xml/com.sun.org.apache.xalan.internal.xsltc.compiler.util.MethodGenerator.outlineChunks(MethodGenerator.java:1168)
Any idea where I am going wrong?

Save modified xml into internal storage Android

I added node in a existing xml file located in /data/data.my.package.app/files/file.xml and I just want to save the file but I didn't find out.
I tried this function seen in an other post :
private void save(Document newDoc) throws Exception{
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StreamResult result = new StreamResult(new File(context.getFilesDir().getAbsolutePath() + "/file.xml"));
Source source = new DOMSource(newDoc);
transformer.transform(source, result);
}
But I get an null pointer exception on tranformer.transform() ... This is how I initialise my Document file.
FileInputStream is = new FileInputStream(context.getFilesDir().getAbsolutePath() + "/file.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(is);
Thanks a lot for the help
A.D
The file cannot be new.
Must be already present:
StreamResult result =
new StreamResult(new File(context.getFilesDir().getAbsolutePath() + "/file.xml"));
for me this work:
//save the doc as string in a text file with the same name (extension .xml)
save(this, body, dir, FILENAME_XML);
//apply the transformer
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory_p.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(
new File(dir+File.separator+FILENAME_XML));
transformer.transform(source, result);
the file xml is produced.

Unable to add doctype tag to xml file using java

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

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

Categories