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????
Java Code to Convert an XML Document to String For converting the XML Document to String, we will use TransformerFactory , Transformer and DOMSource classes. "</BookStore>"; //Call method to convert XML string content to XML Document object.
Document convertStringToDocument(String xmlStr) : This method will take input as String and then convert it to DOM Document and return it. We will use InputSource and StringReader for this conversion. String convertDocumentToString(Document doc) : This method will take input as Document and convert it to String.
DOMDocument implements the DOM API - access nodes via things like getElementById(), getElementsByClassName() , etc, and use saveXML() to write out a string.
DOM Parser is the easiest java xml parser to learn. DOM parser loads the XML file into memory and we can traverse it node by node to parse the XML. DOM Parser is good for small files but when file size increases it performs slow and consumes more memory.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With