DOM - DOM transformation
Hi all,
I need to apply an XSL transformation to a DOM and I want to get a DOM as a result. This is no problem with Xalan or Saxon.
I also want to use the Oracle XSL processor. Now this is where the problem starts: This processor tells me it only accepts SAX sources.
My current workaround is this:
1) transform DOM to String
2) use String as a StreamSource, apply transformation, store result as String
3) parse the resulting String as a DOM
This
* doesn't seem to be very elegant
* is bound to have bad performance
* actually seems to cause a problem because a namespace declaration is missing in the serialized transformation result and I cannot parse the result as a DOM (this happens very rarely, I have only encountered one transformation that had the problem, about 50 others seem to be fine...)
What's the "proper" way of doing this?
Thanks in advance for any insights!
Hello dvorah,
sorry for the late reply: There are no (email) notifications when a posting is edited and I therefore totally missed your correction...
Well anyway: Unfortunately, those two links don't help at all, because they basically just describe what I am already doing (see above).
Bottom line (of those postings) is: Can't be done. (except with "brute force" serialization and reparsing).
Those postings are MORE THAN EIGHT YEARS OLD (spring of 2001) when Java 1.3 (!) was current and I'm really hoping that things have changed since then... I've done XML handling back then and it was a major pain (I quite like it now since Java 5)
The way I see it, I could probably come up with a much much better solution (for one half of the problem) myself in a couple of hours (a SAX ContentHandler that builds a DOM from the events), I just don't feel like I should have to do that :-(((
Similar Messages
-
DOM Parser Transformer and tags without value
hi all
i;m trying to modify an xml
the code is given below.
DOMSource source = new DOMSource(a_doc);
StreamResult result = new StreamResult(new FileOutputStream(a_path));
TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer transformer = transFactory.newTransformer();
transformer.transform(source, result);
my problem is a tag with no value lake <tag></tag> it is converted into <tag /> in the result.
can anybody help me to get the tag as it is?hi patterson,
i'm just changing the values of some tags.
the code i'm using is given below.
NodeList nodeList = a_doc.getElementsByTagName(a_elementNodeName);
int rootNodeListLen = nodeList.getLength();
for(int i=0;i<rootNodeListLen;i++)
System.out.println("inside element");
Node rootNode = nodeList.item(i);
if(rootNode == null) continue;
String parentNodeName = rootNode.getParentNode().getNodeName();
if(parentNodeName!=null )
if(rootNode.getFirstChild() == null) continue;
String value = rootNode.getFirstChild().getNodeValue();
if(a_hashTable.containsKey(value))
rootNode.getFirstChild().setNodeValue((String) a_hashTable.get(value));
can u help me on this? -
when signing in to my yoono account and using yoono, a window starts opening showing this message, it will not allow me to continue working, in order for me to continue using firefox, I have to close the browser, open it and close the yoono app
when signing in to my yoono account and using yoono, a window starts opening showing this message, it will not allow me to continue working, in order for me to continue using firefox, I have to close the browser, open it and close the yoono app
-
Losing "xmlns" when transforming DOM to XML file in OC4J
I am outputting a DOM to a file using the standard transformation approach. When executed within JDeveloper everything works fine. However, when wrapped in a webservice using JDeveloper and run within OC4J the output is missing the "xmlns" attribute from the root node. Anyone have an idea why this is happening and what a workaround would be?
The original XML root element is:
<e2579ReportAssemblyList xmlns="http://cdrh.fda.gov/schema/e2579ReportAssembly.xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema-instance" xs:noNamespaceSchemaLocation="http://cdrh.fda.gov/schema/e2579ReportAssembly.xsd e2579ReportAssembly.xsd">
You can see the xmlns attribute has been provide. I have verified that the attributes are correct while in the DOM.
The xml root element after saving to DOM using transformation is:
<e2579ReportAssemblyList xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema-instance" xs:noNamespaceSchemaLocation="http://cdrh.fda.gov/schema/e2579ReportAssembly.xsd e2579ReportAssembly.xsd">
You can see the xmlns attribute is now blank.
The approach used in the transformation is as follows:
File mOutput = new File(mFileNamePath);
FileOutputStream mOutputStream = new FileOutputStream(mOutput);
Transformer mTransformer = TransformerFactory.newInstance().newTransformer();
mTransformer.transform(new DOMSource(mNextBatchItem), new StreamResult(mOutputStream));
mOutputStream.close();
Any suggestions would be greatly appreciated.If no one knows why this is happening in the transform, is there another reliable way of outputting the DOM to an XML file?
-
String to org.w3c.dom.Document conversion problem
Hi all
I am using JDK 5 and am having scenario to convert String to w3c.Document object , by the way of finding solution i got a code snippet in sun forum
final String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><DATA>sample</DATA>"; // xml to convert
final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
final DocumentBuilder builder = factory.newDocumentBuilder();
final Document document = builder.parse(new InputSource(new StringReader(xml)));
System.out.println(document);
But when i try to execute this code , am gettng output as null. , i dont know why this code behaving like that , can you please help me to solve the problem?
Thanks
Prabu.Pimprabu wrote:
I am using JDK 5 and am having scenario to convert String to w3c.Document object, by the way of finding solution i got a code snippet in sun forum
System.out.println(document);
Hi Prabu,
This is not the way you can print a DOM Document. You can do it using Transformer:
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><DATA>sample</DATA>"; // xml to convert
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(xml)));
//Wong Way of printing a DOM Document. this equal to Object.toString(), Which is of no use for you.
System.out.println(document); // It will just print: [#document: null]
// Using Transformer to print DOM Document
Transformer transformer = TransformerFactory.newInstance().newTransformer();
Source source = new DOMSource(document);
Result output = new StreamResult(System.out);
transformer.transform(source, output); // This will print: <?xml version="1.0" encoding="UTF-8"?><DATA>sample</DATA>*Cheers,
typurohit* (Tejas Purohit) -
Save DOM tree with XIncludeAware
Hi everybody,
i read in a XML structure (that is divided into several XML files through xinclude) by using this code:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setXIncludeAware(true);
dbf.setNamespaceAware (true);
//include schema
dbf.setSchema(schema);
DocumentBuilder dom;
dom = dbf.newDocumentBuilder();
dom.setErrorHandler(eh);
document = dom.parse(new File(xml));XML structure:
xml_global.xml
xml_local1.xml
local11.xml
local12.xml
xml_local2.xml
local21.xml
local22.xmlNow i want to save the XML structure back to the different XML files of the source with the xinclude tags.
is there a way to handle this?
Hope you can help me
Edited by: Silence66 on Jun 13, 2008 1:35 AMThose "xinclude tags" (as you call them) are just some XML elements, aren't they? Then just write those XML elements.
Or is your question that you need to know what got included via XInclude and you need to reverse the process? -
Error while transforming XSLT by calling function with Reflection API
Hi,
I'm new to Reflection API. I want to call function from the jar file which is not in my application context. So I have loaded that jar ( say XXX.jar) file at runtime with URLClassLoader and call the function say [ *myTransform(Document document)* ]. Problem is that when I want to transform any XSLT file in that function it throws exception 'Could not compile stylesheet'. All required classes are in XXX.jar.
If I call 'myTransform' function directly without reflection API then it transformation successfully completed.
Following is code of reflection to invoke function
ClassLoader contextCL = Thread.currentThread().getContextClassLoader();
URLClassLoader loader = new URLClassLoader(jarURLs, contextCL);
Class c = loader.loadClass(fullClasspath);
Constructor constructor = c.getDeclaredConstructor(constructorParamsClasses);
Object instance = constructor.newInstance(constructorParams);
Method method = c.getDeclaredMethod("myTransform", methodParamsClasses);
Object object = method.invoke(instance, methodParams);Following is function to be called with reflection API.
public Document myTransform ( Document document ) {
// Reference of Document (DOM NODE) used to hold the result of transformation.
Document doc = null ;
// DocumentBuilderFactory instance which is used to initialize DocumentBuilder to create newDocumentBuilder.
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance () ;
// Reference of DocumentBuilder used to create new Document (DOM NODE).
DocumentBuilder builder;
try {
// Initialize DocumentBuilder by using DocumentBuilderFactory instance.
builder = factory.newDocumentBuilder ();
// Initialize new document instance by using DocumentBuilder instance.
doc = builder.newDocument () ;
// Creates new DOMSource by using document (DOM NODE) which is coming through current transform() method parameter.
DOMSource domsource = new DOMSource ( document ) ;
// Creates new instance of TransformerFactory.
TransformerFactory transformerfactory = TransformerFactory.newInstance () ;
// Creates new Transformer instance by using TransformerFactory which holds XSLT file.
Transformer transformer = null;
********* exception is thrown from here onward ******************
transformer = transformerfactory.newTransformer (new StreamSource (xsltFile));
// Transform XSLT on document (DOM NODE) and store result in doc (DOM NODE).
transformer.transform ( domsource , new DOMResult ( doc ) ) ;
} catch (ParserConfigurationException ex) {
ex.printStackTrace();
} catch (TransformerConfigurationException ex) {
ex.printStackTrace();
} catch (TransformerException ex) {
ex.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
//holds result of transformation.
return doc ;
}Following is full exception stacktrace
ERROR: 'The first argument to the non-static Java function 'myBeanMethod' is not a valid object reference.'
FATAL ERROR: 'Could not compile stylesheet'
javax.xml.transform.TransformerConfigurationException: Could not compile stylesheet
at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl.newTemplates(TransformerFactoryImpl.java:829)
at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl.newTransformer(TransformerFactoryImpl.java:623)
at com.actl.dxchange.utilities.Transformation.transform(Transformation.java:83)
at com.actl.dxchange.base.BaseConnector.transform(BaseConnector.java:330)
at com.actl.dxchange.connectors.KuoniConnector.doRequestProcess(KuoniConnector.java:388)
at com.actl.dxchange.connectors.KuoniConnector.hotelAvail(KuoniConnector.java:241)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
...........Hi,
Thanks for response.
Following is code for setting 'methodParamsClasses' array object. I do ensure that Document is not null and valid. My application is web application.
Document requestObj = /* my code for generating Document object*/
Object[] methodParams = new Object[]{requestObj}
Class[] methodParamsClasses = new Class[]{};
if (methodParams != null) {
methodParamsClasses = new Class[methodParams.length];
for (int i = 0; i < methodParams.length; i++) {
if (methodParams[i] instanceof Document) {
/************** if parameter is instance of Document then I set class type as "Document.class" ***********/
methodParamsClasses[i] = Document.class;
} else {
methodParamsClasses[i] = methodParams.getClass(); -
XSLT Transform in XML Signature: Exception
Hello,
I have following problem with an XSLT tranform in my XML signature. Here is the code I use to add XSLT to signature:
main() {
DOMStructure stylesheet = new DOMStructure( getStylesheet() );
XSLTTransformParameterSpec spec = new XSLTTransformParameterSpec( stylesheet );
transforms.add( fac.newTransform( Transform.XSLT, spec ) );
private Element getStylesheet() throws Exception {
String stylesheet = //"<?xml version=\"1.0\"?>" +
"<xslt:stylesheet version=\"1.0\" xmlns:xslt=\"http://www.w3.org/1999/XSL/Transform\">\n" +
" <xsl:include href=\"http://extern XSLT\" />\n" +
" <xslt:template match=\"/\">" +
" <xsl:apply-imports />" +
" </xslt:template>" +
"</xslt:stylesheet>\n";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//dbf.setValidating( true );
return dbf.newDocumentBuilder().parse( new ByteArrayInputStream( stylesheet.getBytes() ) ).getDocumentElement();
I get following exception:
javax.xml.crypto.dsig.XMLSignatureException: javax.xml.crypto.dsig.TransformException: com.sun.org.apache.xml.internal.security.transforms.TransformationException: Cannot find xslt:stylesheet in Transform
Original Exception was com.sun.org.apache.xml.internal.security.transforms.TransformationException: Cannot find xslt:stylesheet in Transform
at org.jcp.xml.dsig.internal.dom.DOMReference.transform(Unknown Source)
at org.jcp.xml.dsig.internal.dom.DOMReference.digest(Unknown Source)
at org.jcp.xml.dsig.internal.dom.DOMXMLSignature.digestReference(Unknown Source)
at org.jcp.xml.dsig.internal.dom.DOMXMLSignature.sign(Unknown Source)
In google I cannot find any details what can be wrong.
Any suggestions?
Thanks in advance,
errnoThanks for your response. Sorry - I tried both versions with xslt and xsl - doesn't worked -> the error in my post is actually caused through the multiple changes of this part of code. Here once again:
private Element getStylesheet() throws Exception {
String stylesheet = //"<?xml version=\"1.0\"?>" +
"<xslt:stylesheet version=\"1.0\" xmlns:xslt=\"http://www.w3.org/1999/XSL/Transform\">\n" +
" <xslt:include href=\"external XSLTl\" />\n" +
" <xslt:template match=\"/\">" +
" <xslt:apply-imports />" +
" </xslt:template>" +
"</xslt:stylesheet>\n";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//dbf.setValidating( true );
return dbf.newDocumentBuilder().parse( new ByteArrayInputStream( stylesheet.getBytes() ) ).getDocumentElement();
Thanks,
errno -
Do not include ?xml version="1.0" encoding="UTF8" when transform?
I try to Output correctly XML(sox) from DOM with transformer. The first two lines of output should like this
<?soxtype PurchaseOrder urn:x-commerceone:document:com:commerceone:CBL:CBL.sox$1.0?>
<?import PurchaseOrder urn:x-commerceone:document:com:commerceone:CBL:CBL.sox$1.0?> .
But what I get always inclue <?xml version="1.0" encoding="UTF-8" ?> ,how can I remove this line when transform?
Thanks in advance.well, you get a legal regular XML prolog in your XML file.
without it, your file can't really be called an XML file...
if you don't want it, you can try changing the output type to "text", so you will get an XML looking text file, with no problem.
but of course this is not really serious. -
JAXP transform outputs ' instead of '
When I output DOM using Transformer <,>,& and " are escaped but single quote isn't.
Is there a way to force Transformer to escape single quote character?you can easily achieve this goal with the following method:
1. create your own XML Entity Resolution file, by using the one provided with JAXP as example, adding any necessary entity (apos in this case):
# $Id: XMLEntities.res,v 1.1 2000/12/06 05:37:09 sboag Exp $
# @version $Revision: 1.1 $ $Date: 2000/12/06 05:37:09 $
# @author <a href="mailto:[email protected]">Assaf Arkin</a>
# Character entity references for markup-significant
quot 34
amp 38
lt 60
gt 62
apos 392. Specify to the transformer that it must use this file when outputting the DOM:
transformer.setOutputProperty("{http://xml.apache.org/xslt}entities", "file://c:/temp/myXMLEntities.res");Voila! you're all set.
D. -
Hello,
I build a DOM tree in my applet.
Then I transform it to XML String.
But since the JRE 1.4.2_05 it doesn't work.
These lines failed because these variables became final:
org.apache.xalan.serialize.CharInfo.XML_ENTITIES_RESOURCE = getClass().getResource("XMLEntities.res").toString();
org.apache.xalan.processor.TransformerFactoryImpl.XSLT_PROPERTIES = getClass().getResource("XSLTInfo.properties").toString();The rest of the code :
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document domXML = builder.newDocument();
// I build my DOM Tree
StringWriter xmlResult = new StringWriter();
Source source = new DOMSource(domXML);
Result result = new StreamResult(xmlResult);
Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.setOutputProperty(javax.xml.transform.OutputKeys.INDENT,"yes");
xformer.transform(source,result);Is there any other way to get an XML String from a DOM tree in an applet ?
I'm so disappointed to note this big problem.Does anyone have an idea why I get this error message when try to use transform in an applet?
Thanks...
java.lang.ExceptionInInitializerError
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at org.apache.xalan.serialize.SerializerFactory.getSerializer(Unknown Source)
at org.apache.xalan.transformer.TransformerIdentityImpl.createResultContentHandler(Unknown Source)
at org.apache.xalan.transformer.TransformerIdentityImpl.transform(Unknown Source)
at matrix.CreateMtrx.SaveDoc(CreateMtrx.java:434)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at thinlet.Thinlet.invokeImpl(Unknown Source)
at thinlet.Thinlet.invoke(Unknown Source)
at thinlet.Thinlet.handleMouseEvent(Unknown Source)
at thinlet.Thinlet.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Caused by: java.lang.RuntimeException: The resource [ XMLEntities.res ] could not load: java.net.MalformedURLException: no protocol: XMLEntities.res
XMLEntities.res java.net.MalformedURLException: no protocol: XMLEntities.res
at org.apache.xalan.serialize.CharInfo.<init>(Unknown Source)
at org.apache.xalan.serialize.SerializerToXML.<clinit>(Unknown Source)
... 28 more -
Using transform api with xslt and DOM Nodes
Hi,
when trying to transform a xml document with xslt using the javax.xml.transform api
providing an element node of a previously parsed document, I find that absolute
paths are not recognized.
The following program shows what I am basically doing (the class can be executed
on the command line providing a stylesheet and xml instance):
import java.io.*;
import org.w3c.dom.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import javax.xml.parsers.*;
class Transform {
public static void main(String [] args) throws Exception {
TransformerFactory tfactory = TransformerFactory.newInstance();
Transformer transformer = tfactory.newTransformer(new StreamSource(args[0]));
DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
DocumentBuilder parser = dfactory.newDocumentBuilder();
Document doc = parser.parse(args[1]);
Element domElem = doc.getDocumentElement();
// workaround
// StringWriter out = new StringWriter();
// Transformer id = tfactory.newTransformer();
// id.transform(new DOMSource(domElem),new StreamResult(out));
// String xml = out.toString();
// transformer.transform(new StreamSource(new StringReader(xml)), new StreamResult(System.out));
transformer.transform(new DOMSource(domElem), new StreamResult(System.out));
transformer.clearParameters();
If I use this on e.g.
xsl:
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes" encoding="ISO-8859-1" method="xml"/>
<xsl:template match="/">
<xsl:value-of select="/foo/bar"/>
</xsl:template>
</xsl:stylesheet>
xml:
<foo>abc<bar>def</bar></foo>
I get
<?xml version="1.0" encoding="ISO-8859-1"?>
abcdef
instead of
<?xml version="1.0" encoding="ISO-8859-1"?>
def
I think this is due to the fact, that the transformation does not recognize
any absolutely adressed xpath correctly.
From what I read in the API docs, I think what I'm doing should be ok.
So: did I misunderstand something or is this a bug in the java libraries?
I'm using j2sdk 1.4.1_01 on i386 linux.
If I use the commented code (serializing the xml and doing the transformation
with a StreamSource, that has to be parsed again), everything's fine.
Of course it would be easier to parse the file directly in the example but in the
real program, I already have a dom tree and want to transform a part of it.
Any help appreciated.
Thanks, Moruswhy?
that's all the point of XSL: define what part of your
XML you want in your XSL templates, there is no need
to prepare a sub-DOM of your DOM.
Ok. Right. That's an alternative.
The problem remains, that there are some stylesheets originally written
for the current solution and though they should work with the whole document
as well, it's not certain.
Actually I don't know if this ever worked. I did neither write this code nor maintained the system so far.
btw. you would be faster by giving a StreamSource to
your transformation.Probably yes. But that would imply to rewrite a lot of code.
What is happening is:
there is a SOAP answser containing a xml document as the result parameter.
The SOAP answer is parsed (I guess by the soap classes already) and the
result xml is extracted. That's where the element node I'm trying to transform
stems from.
Besides, I still don't see why DOMSource takes any node if only document nodes
work.
Thanks, Morus -
Exception using JAXP transformer on non-default DOM
Hi!
I have a problem with the JAXP integration of my own DOM implementation. I've written a compressed core level 1 DOM implementation and integrated it into JAXP by writing a DocumentBuilder and a DocumentBuilderFactory class. Although not 100% of all DOM methods are implemented completely, it works fine for typical xml documents. I can read in a xml document using JAXP by setting the DocumentBuilderFactory setting to my implementation:
System.setProperty("javax.xml.parsers.DocumentBuilderFactory", "ddom.jaxp.DDocumentBuilderFactory");
But if I try to use a Transformer on the document, I get a NoSuchMethodException:
Exception in thread "main" java.lang.NoSuchMethodError
at org.apache.xpath.DOM2Helper.getNamespaceOfNode(DOM2Helper.java:348)
at org.apache.xml.utils.TreeWalker.startNode(TreeWalker.java:281)
at org.apache.xml.utils.TreeWalker.traverse(TreeWalker.java:119)
at org.apache.xalan.transformer.TransformerIdentityImpl.transform(TransformerIdentityImpl.java:320)
at ddom.DTreeTester.write(DTreeTester.java:59)
at ddom.DTreeTester.main(DTreeTester.java:76)
Unfortunately there is no source code available for JAXP, so I can't really figure what's going wrong. From the exception it is obvious that the Transformer is trying to figure out the namespace before it crashes. As my implementation ony implements DOM level 1 at the moment there is no support for namespaces. But of course this is reported by my DocumentBuilder class, so no calls to such methods hould occur.
I just wanted to use the identity transformation to produce some nice output files. I would be very happy if anyone could help me with this problem.
MathiasI tried to get more info on the DOM2Helper class, but only found lots of deprecated APIs. There seems to be some work done on internal APIs dealing with that class. Search for "DOM2Helper" in this page http://xml.apache.org/xalan-j/readme.html
Maybe you just need to get a newer version of Xalan. -
How to transform DOM into String
Hi,
Can any one provide an example of transforming DOM into String using TransformationFactory or any other API of JAXP?
Regards...
ShamitAnd for finer output:
* Prints a textual representation of a DOM object into a text string..
* @param document DOM object to parse.
* @return String representation of <i>document</i>.
static public String toString(Document document) {
String result = null;
if (document != null) {
StringWriter strWtr = new StringWriter();
StreamResult strResult = new StreamResult(strWtr);
TransformerFactory tfac = TransformerFactory.newInstance();
try {
Transformer t = tfac.newTransformer();
t.setOutputProperty(OutputKeys.ENCODING, "iso-8859-1");
t.setOutputProperty(OutputKeys.INDENT, "yes");
t.setOutputProperty(OutputKeys.METHOD, "xml"); //xml, html, text
t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
t.transform(new DOMSource(document.getDocumentElement()), strResult);
} catch (Exception e) {
System.err.println("XML.toString(Document): " + e);
result = strResult.getWriter().toString();
return result;
}//toString() -
Transform of a DOM document to a file results in abstractmethoderror
PrintWriter printWriter = new PrintWriter(fileWriter);
TransformerFactory transformerFactory = TransformerFactory
.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(document);
Result result = new StreamResult(printWriter);
transformer.transform(source, result);
printWriter.close();This results in:
Exception in thread "main" java.lang.AbstractMethodError: org.apache.xerces.dom.DocumentImpl.getXmlStandalone()Z
at com.sun.org.apache.xalan.internal.xsltc.trax.DOM2TO.setDocumentInfo(Unknown Source)
at com.sun.org.apache.xalan.internal.xsltc.trax.DOM2TO.parse(Unknown Source)
at com.sun.org.apache.xalan.internal.xsltc.trax.DOM2TO.parse(Unknown Source)
at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.transformIdentity(Unknown Source)
at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.transform(Unknown Source)
at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.transform(Unknown Source)
at be.dolmen.CostApplication.service.impl.XMLReport.writeXMLForMonth(XMLReport.java:165)
at be.dolmen.CostApplication.service.impl.XMLDataImpl.checkPreviousXML(XMLDataImpl.java:116)
at be.dolmen.CostApplication.service.impl.XMLDataImpl.<init>(XMLDataImpl.java:75)
at be.dolmen.CostApplication.main.MainServer.xmlOutput(MainServer.java:177)
at be.dolmen.CostApplication.main.MainServer.main(MainServer.java:123)The strange thing is that this:
TransformerFactory tranFact = TransformerFactory.newInstance();
Transformer transfor = tranFact.newTransformer(xslSource);
// HTML file
FileWriter fileWriterHtml = new FileWriter(homePathHtml
+ File.separator + year + month + File.separator
+ employee.getEmpid() + ".html");
PrintWriter printWriterHtml = new PrintWriter(fileWriterHtml);
Result dest = new StreamResult(printWriterHtml);
// TRANSFORM
transfor.transform(source, dest);works! So I give an XSLSource in the TransFormer and I'm using THE SAME document. What am I doing wrong? I just want to print out the DOM XML file ... :-(Hi Karan,
JAXP is designed with a pluggability layer, which means that users are free to choose or move to any implementation they prefer. The mechanism JAXP uses to find a particular implementation looks like this, using DocumentBuilderFactory as an example:
1. The value of a system property javax.xml.parsers.DocumentBuilderFactory
2. The contents of the file $JAVA_HOME/lib/jaxp.properties
3. The Jar Service Provider discovery mechanism specified in the Jar File Specification. A jar file can have a resource such as META-INF/services/javax.xml.parsers.DocumentBuilderFactory containing the name of the concrete class to instantiate.
4. The fallback platform default implementation.
The JDK comes with a Sun implementation (check out jaxp.dev.java.net for details), that is, jaxp 1.3 in JDK5 and jaxp 1.4 in JDK6. So if not specified, JAXP falls back to these default implementation.
In your case, because you have the Xerces 2.0.2 jar file on the classpath, the factory will find the Xerces 2.0.2 implementation and use it. The result is that the document was created using Xerces 2.0.2 which, as you noticed, is not compatible with the default XSLT implementation in the JDK. So to answer your question, the transformer was using the java 1.6 implementation. It's the document that was created using the Xerces 2.0.2 (in my case) implementation.
To solve the problem, you may remove Xerces 2.0.2 from the classpath if there's no other dependencies. Or force the document to be created using JDK default in this part of the code.
Maybe you are looking for
-
When I delete desktop icons, they don't auto arrange?
Hi everyone. I purchased a new macbook pro about a month and a half ago and am running snow leopard on it. When I delete icons on my desktop, the gap where the icon used to be is still there. I would like my desktop to automatically fill that in with
-
Cannot get past screen 2 of 2 for iTunes Music Store purchase of music
I can't get help from Apple or ITunes or anyone - They sent me here. I have tried to buy music at the ITunes store since Dec 20- No luck here's the story (email to iTunes were of NO HELP!! - Canned responses are useless) 1. Entered credit card inform
-
Power of function with very large numbers & HEX array
Hello, I'm haveing 3 problems and I would be greatful if someone can help. I've attached 1) I need to calculate 982451653^15. I've used 'Power of X' function but the resut I'm getting is incorrect. is there a way for getting correct result?? 2) after
-
[SOLVED] Date of last pacman upgrade
Hello! In Bash, is there a way of obtaining a timestamp signifying when the last full system upgrade was done with pacman? Last edited by ibes (2013-10-25 06:48:38)
-
Loading ITunes files from external to winows 8.
I had a windows7 laptop crash with 136 G s of music in ITunes. I had it all backed up on an external drive. I now have a windows 8 laptop and want to load those files on the newly downloaded itunes. I put alot of work into rating and building playlis