8

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.

4

2 回答 2

16

你为什么要构建一个 DOMSource?如果你想要的只是一个源作为转换的输入,那么提供一个 StreamSource 会更有效,你可以这样做

new StreamSource(new StringReader(fileData))

最好也提供一个systemId。构建 DOM 是浪费时间。

于 2013-05-20T15:30:50.213 回答
1

仅供参考:没有类 DOMSource 的构造函数,其参数只有字符串,如 DOMSource(String)。
构造函数如下:
i)DOMSource()
ii)DOMSource(Node n)
iii)DOMSource(Node node, String systemID)
请参见:http ://docs.oracle.com/javase/6/docs/api/javax/xml/transform/dom/DOMSource.html

于 2013-05-20T13:38:15.377 回答