Here you can find the source of encodeStringIntoMemento(String str)
public static String encodeStringIntoMemento(String str)
//package com.java2s; /******************************************************************************* * Copyright (c) 2015 Ericsson and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors://from w w w. j a v a2s. c om * Marc Dumais (Ericsson) - initial API and implementation (bug 460837) *******************************************************************************/ import java.io.ByteArrayOutputStream; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; 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 { protected static final String ROOT_ELEMENT_TAGNAME = "root_element"; protected static final String ELEMENT_TAGNAME = "elem"; protected static final String ATTRIBUTE_VALUE = "value"; /** Returns a XML memento, that encodes a single String parameter */ public static String encodeStringIntoMemento(String str) { List<String> list = new ArrayList<>(); list.add(str); return encodeListIntoMemento(list); } /** Returns a XML memento, that encodes a List of Strings */ public static String encodeListIntoMemento(List<String> labels) { String returnValue = null; DocumentBuilderFactory dfactory = DocumentBuilderFactory .newInstance(); DocumentBuilder docBuilder = null; try { docBuilder = dfactory.newDocumentBuilder(); Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement(ROOT_ELEMENT_TAGNAME); doc.appendChild(rootElement); // create one XML element per list entry to save for (String lbl : labels) { Element elem = doc.createElement(ELEMENT_TAGNAME); elem.setAttribute(ATTRIBUTE_VALUE, lbl); rootElement.appendChild(elem); } ByteArrayOutputStream s = new ByteArrayOutputStream(); TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$ transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$ DOMSource source = new DOMSource(doc); StreamResult outputTarget = new StreamResult(s); transformer.transform(source, outputTarget); returnValue = s.toString("UTF8"); //$NON-NLS-1$ } catch (Exception e) { e.printStackTrace(); } return returnValue; } }