简体   繁体   中英

Getting xml string from Document in Java

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.*;

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

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();

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

String xmlString =  org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(doc);

The method org.apache.axis.utils.XMLUtils.PrettyDocumentToString(Document) have a problem that includes white spaces in the tag values.

A solution is use the method org.apache.axis.utils.XMLUtils.DocumentToString(Document).

I'm also looking for a cheap and efficient way to serialize a DOM. Until now, I see only 2 options:

Maybe you can try the LSSerializer approach (but not in one call).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM