For Beginners – Java file to convert XML Document to String representation
November 17th, 2009
No comments
The below Java file shows how to create a XML Document, append Elements to it and finally convert the XML Document to String representation. I am posting this as I noticed many of theĀ developers in my team were using StringBuffer (or StringBuilder) to create the String representation of the XML.
import java.io.StringWriter;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* Class to construct string representation of XML rather than using StringBuffer or StringBuilder which is cumbersome.
*
*/
public class XMLStringCreator {
private Document document = null;
public XMLStringCreator() throws ParserConfigurationException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.newDocument();
}
/**
* Creates an xml element with the details passed.
* @param elementName XML element name
* @param textNodeValue null if there is no text node value to be associated.
* @param attributesNameValueMap should pass null or an empty Map if no attributes
* @return The XML Element with attributes specified (if any)
*/
public Element createElement(String elementName, String textNodeValue, Map<String, String> attributesNameValueMap) {
Element element = document.createElement(elementName);
if (textNodeValue != null) {
element.appendChild(document.createTextNode(textNodeValue));
}
if (attributesNameValueMap == null || attributesNameValueMap.size() == 0) {
return element;
} else {
return addAttributes(element, attributesNameValueMap);
}//eof else
}
/**
* This method should be called only once. Its the responsibility of the caller to ensure this.
* @param root The root xml element
*/
public void addRootElement(Element root) {
document.appendChild(root);
}
/**
* Appends child to parent xml element (or node)
* @param parent The parent XML element
* @param child The child xml element
*/
public void addChild(Element parent, Element child) {
parent.appendChild(child);
}
/**
* returns the XML string constructed so far with the other methods of this class.
* @return xml string representation.
* @throws Exception
*/
public String getXMLString() throws Exception {
StringWriter writer = new StringWriter();
Result result = new StreamResult(writer);
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.transform(new DOMSource(document), result);
return writer.toString();
}
/**
* Adds attributes to XML element
* @param element
* @param attributesNameValueMap
* @return The xml element with the attributes.
*/
private Element addAttributes(Element element, Map<String, String> attributesNameValueMap) {
for (String key : attributesNameValueMap.keySet()) {
element.setAttribute(key, attributesNameValueMap.get(key));
}//eof for loop
return element;
}
@Override
public String toString(){
throw new UnsupportedOperationException("Please use the method getXMLString instead");
}
}