turlife
turlife

Reputation: 121

How can I convert a String to a DOMSource in Java?

I need some help. In my String filedata variable I stored an XMLdocument. Now I want to convert this variable to a DOMSource type and use this code:

DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = db.parse( new InputSource( new StringReader( filedata ) ) ); 
DOMSource source = new DOMSource(doc);

and transform by javax.xml.transform.Transformer :

 Transformer transformer = XMLTransformerFactory.getTransformer(messageType);
 StreamResult res = new StreamResult(flatXML);
 transformer.transform(source, res);

But my flatXML is empty after transformation. I checked my doc variable, and it contains my XML document and parsed everything right. If I change my source to the real path everything is ok and works fine :

 Source source = new StreamSource("c:\\temp\\log\\SMKFFcompleteProductionPlan.xml");

I think my problem situated in this line of code :

DOMSource source = new DOMSource(doc);

but I don't know how to solve this problem.

Upvotes: 8

Views: 14908

Answers (2)

Michael Kay
Michael Kay

Reputation: 163595

Why are you trying to construct a DOMSource? If all you want is a source to supply as input to a transformation, it is much more efficient to supply a StreamSource, which you can do as

new StreamSource(new StringReader(fileData))

preferably supplying a systemId as well. Constructing the DOM is a waste of time.

Upvotes: 17

Shreyos Adikari
Shreyos Adikari

Reputation: 12754

FYI: There are no constructor of Class DOMSource having argument only String like DOMSource(String).
The constructors are as follows:
i)DOMSource()
ii)DOMSource(Node n)
iii)DOMSource(Node node, String systemID)
Please see : http://docs.oracle.com/javase/6/docs/api/javax/xml/transform/dom/DOMSource.html

Upvotes: 2

Related Questions