从Java中的Document获取xml字符串 [英] Getting xml string from Document in Java

查看:477
本文介绍了从Java中的Document获取xml字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Java程序,旨在考虑使用xml dom并将其写入字符串。
我正在使用这些软件包: org.w3c.dom。* javax.xml.parsers。*;

I have a Java program aiming to consider an xml dom and write it into a string. I am using these packages: org.w3c.dom.* and javax.xml.parsers.*;

所以我有 DocumentBuilder 文件元素对象...

So I have DocumentBuilder, Document, Element objects...

有没有办法在一次调用中获取代表我的xml dom的字符串? ??

Is there a way to get the string representing my xml dom in one call????

推荐答案

这不是一个电话,但是:

Its not one call but:

TransformerFactory transfac = TransformerFactory.newInstance();
Transformer trans = transfac.newTransformer();
trans.setOutputProperty(OutputKeys.METHOD, "xml");
trans.setOutputProperty(OutputKeys.INDENT, "yes");
trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", Integer.toString(2));

StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(doc.getDocumentElement());

trans.transform(source, result);
String xmlString = sw.toString();

setOutputProperty方法使字符串输出更漂亮,因此您可以将其取出。

The setOutputProperty method makes the string output prettier so you can take it out.

这篇关于从Java中的Document获取xml字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆