Java XML String Transform createXmlError(String message, String details)

Here you can find the source of createXmlError(String message, String details)

Description

create Xml Error

License

Open Source License

Declaration

public static String createXmlError(String message, String details) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
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;

public class Main {
    public static String createXmlError(String message, String details) {
        try {/*from w w w .jav  a  2 s. c o m*/
            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            Document document = docBuilder.newDocument();

            Element rootElement = document.createElement("error");

            Element messageElement = document.createElement("message");
            if (message != null) {
                messageElement.setTextContent(message);
            } else {
                messageElement.setTextContent("internal error");
            }
            rootElement.appendChild(messageElement);

            if (details != null) {
                Element detailsElement = document.createElement("error-details");
                detailsElement.setTextContent(details);
                rootElement.appendChild(detailsElement);
            }

            document.appendChild(rootElement);

            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            StringWriter sw = new StringWriter();
            Result output = new StreamResult(sw);
            Source input = new DOMSource(document);

            transformer.transform(input, output);

            return sw.toString();
        } catch (Exception e) {
            return "<?xml version=\"1.0\" encoding=\"UTF-8\"?><error><message>internal error</message></error>";
        } catch (Error e) {
            return "<?xml version=\"1.0\" encoding=\"UTF-8\"?><error><message>internal error</message></error>";
        }
    }
}

Related

  1. createSettingsXml(Map props)
  2. createSource(final String message)
  3. createSource(String msg)
  4. createString(Element element)
  5. createXml(ArrayList nameList, ArrayList stringList, ArrayList stringArrayNameList, HashMap> stringArrayContentMap)
  6. createXmlEventReaderOnXmlString(String xml, String docBaseUri)
  7. decodeHex(String hex)
  8. elementToXMLString(Object aElement)
  9. encode(final String value)