Java XML String Transform getXmlStringFromSource(Source payload)

Here you can find the source of getXmlStringFromSource(Source payload)

Description

Method to get formatted Xml string from Xml source

License

CDDL license

Parameter

Parameter Description
payload Source

Return

a formatted Xml string

Declaration

public static String getXmlStringFromSource(Source payload) 

Method Source Code

//package com.java2s;
/*/*  ww w. j  ava2 s  .c o m*/
Copyright (c) 2013 eBay, Inc.
This program is licensed under the terms of the eBay Common Development and
Distribution License (CDDL) Version 1.0 (the "License") and any subsequent  version 
thereof released by eBay.  The then-current version of the License can be found 
at http://www.opensource.org/licenses/cddl1.php and in the eBaySDKLicense file that 
is under the eBay SDK ../docs directory.
*/

import java.io.StringWriter;

import javax.xml.transform.OutputKeys;

import javax.xml.transform.Source;
import javax.xml.transform.Transformer;

import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;

import javax.xml.transform.stream.StreamResult;

public class Main {
    /**
      * Method to get formatted Xml string from Xml source
      *
      * @param payload Source
      * @return a formatted Xml string
      */
    public static String getXmlStringFromSource(Source payload) {
        String result = null;
        StreamResult strResult = new StreamResult(new StringWriter());

        if (payload != null) {
            try {
                TransformerFactory factory = TransformerFactory.newInstance();
                //factory.setAttribute("indent-number", new Integer(2));
                Transformer transformer = factory.newTransformer();
                transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
                transformer.setOutputProperty(OutputKeys.METHOD, "xml");
                transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "1");
                transformer.transform(payload, strResult);
            } catch (TransformerException e) {
                e.printStackTrace();
            }
            result = strResult.getWriter().toString();
        }
        return result;
    }
}

Related

  1. getStreamResultForFile(String filename)
  2. getString(Node node, boolean indent)
  3. getStringFromStreamSource(StreamSource src)
  4. getTemplates(String name)
  5. getValidator(String path)
  6. identity(String xml)
  7. indentXML(String fileContent)
  8. loadSourceFromURL(String systemID)
  9. mergeXml(String... xmlSources)