如何在 Java 中将 String 转换为 DOMSource?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16650469/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 23:34:14  来源:igfitidea点击:

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

javaxml

提问by turlife

I need some help. In my Stringfiledata variable I stored an XMLdocument. Now I want to convert this variable to a DOMSourcetype and use this code:

我需要一些帮助。在我的String文件数据变量中,我存储了一个 XML 文档。现在我想将此变量转换为DOMSource类型并使用以下代码:

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 :

并通过 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 :

但是转换后我的 flatXML 是空的。我检查了我的 doc 变量,它包含我的 XML 文档并正确解析了所有内容。如果我将源更改为真实路径,则一切正常并且工作正常:

 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.

但我不知道如何解决这个问题。

回答by Michael Kay

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

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

new StreamSource(new StringReader(fileData))

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

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

回答by Shreyos Adikari

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

仅供参考:没有像 DOMSource(String) 这样只有 String 参数的 DOMSource 类的构造函数。
构造函数如下:
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