加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 00:04:12 所属栏目:Java 来源:网络整理
导读:我需要一些帮助.在我的String filedata变量中,我存储了一个 XMLdocument.现在我想将此变量转换为DOMSource类型并使用此代码: DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();Document doc = db.parse( new InputSource(
我需要一些帮助.在我的String filedata变量中,我存储了一个 XMLdocument.现在我想将此变量转换为DOMSource类型并使用此代码:
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = db.parse( new InputSource( new StringReader( filedata ) ) ); 
DOMSource source = new DOMSource(doc);

并通过javax.xml.transform.Transformer进行转换:

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

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

Source source = new StreamSource("c:templogSMKFFcompleteProductionPlan.xml");

我认为我的问题位于这行代码中:

DOMSource source = new DOMSource(doc);

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

解决方法

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

最好也提供systemId.构建DOM是浪费时间.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读