How to convert String to DOMSource in Java?

I need help. In my String filedata variable, I saved an XML document. 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 converted using javax.xml.transform.Transformer:

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

But my flatXML is empty after conversion. I checked my doc variable and it contains my XML document and everything parses correctly. If I change my source code to the real path, everything will be fine and works fine:

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

I think my problem is in this line of code:

 DOMSource source = new DOMSource(doc); 

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

+6
source share
2 answers

Why are you trying to build a DOMSource? If all you want is a source for input as a conversion to conversion, it's much more efficient to supply a StreamSource, which you can do as

 new StreamSource(new StringReader(fileData)) 

preferably also providing a system. Building a DOM is a waste of time.

+13
source

FYI: There is no constructor for the DOMSource class that has only the String argument as DOMSource (String).
The constructors are as follows:
i) DOMSource()
ii) DOMSource(Node n)
iii) DOMSource(Node node, String systemID)
See: http://docs.oracle.com/javase/6/docs/api/javax/xml/transform/dom/DOMSource.html

+1
source

Source: https://habr.com/ru/post/945420/


All Articles