Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

xml

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.

like image 375
turlife Avatar asked May 20 '13 13:05

turlife


People also ask

Can we convert string to XML in Java?

Document convertStringToDocument(String xmlStr) : This method will take input as String and then convert it to DOM Document and return it. We will use InputSource and StringReader for this conversion.

What is DOMSource in Java?

public class DOMSource extends Object implements Source. Acts as a holder for a transformation Source tree in the form of a Document Object Model (DOM) tree. Note that XSLT requires namespace support. Attempting to transform a DOM that was not contructed with a namespace-aware parser may result in errors.

What is StreamResult in Java?

public class StreamResult extends Object implements Result. Acts as an holder for a transformation result, which may be XML, plain Text, HTML, or some other form of markup.


2 Answers

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.

like image 180
Michael Kay Avatar answered Oct 06 '22 00:10

Michael Kay


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

like image 42
Shreyos Adikari Avatar answered Oct 05 '22 23:10

Shreyos Adikari