String to formatted XML conversion



import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

public class StringToXML {
 public static String strT0XML(String xmlString) {
  try {
   DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
   InputStream inputStream = new ByteArrayInputStream(xmlString.getBytes());
   Document document = documentBuilder.parse(inputStream);
   TransformerFactory tfactory = TransformerFactory.newInstance();
   DOMSource xmlSource = new DOMSource(document);
   java.io.StringWriter writer = new StringWriter();
   javax.xml.transform.Result result = new javax.xml.transform.stream.StreamResult(writer);
   Transformer serializer = tfactory.newTransformer();
   serializer.setOutputProperty(OutputKeys.INDENT, "yes");
   serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
   serializer.transform(xmlSource, result);
   return writer.toString();
  } catch (TransformerException e) {
   e.printStackTrace();
   throw new RuntimeException(e);
  } catch (ParserConfigurationException e) {
   e.printStackTrace();
  } catch (SAXException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
  return "";
 }
}

No comments:

Post a Comment