Here you can find the source of writePropToString(Properties props)
Parameter | Description |
---|---|
props | a parameter |
Parameter | Description |
---|---|
IOException | an exception |
public static String writePropToString(Properties props) throws IOException
//package com.java2s; /**/*from ww w . ja v a 2 s. c o m*/ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. See accompanying LICENSE file. */ import java.io.IOException; import java.io.StringWriter; import java.util.Enumeration; import java.util.Properties; 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; public class Main { /** * Convert Properties to string * * @param props * @return xml string * @throws IOException */ public static String writePropToString(Properties props) throws IOException { try { org.w3c.dom.Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); org.w3c.dom.Element conf = doc.createElement("configuration"); doc.appendChild(conf); conf.appendChild(doc.createTextNode("\n")); for (Enumeration e = props.keys(); e.hasMoreElements();) { String name = (String) e.nextElement(); Object object = props.get(name); String value; if (object instanceof String) { value = (String) object; } else { continue; } org.w3c.dom.Element propNode = doc.createElement("property"); conf.appendChild(propNode); org.w3c.dom.Element nameNode = doc.createElement("name"); nameNode.appendChild(doc.createTextNode(name.trim())); propNode.appendChild(nameNode); org.w3c.dom.Element valueNode = doc.createElement("value"); valueNode.appendChild(doc.createTextNode(value.trim())); propNode.appendChild(valueNode); conf.appendChild(doc.createTextNode("\n")); } Source source = new DOMSource(doc); StringWriter stringWriter = new StringWriter(); Result result = new StreamResult(stringWriter); TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); transformer.transform(source, result); return stringWriter.getBuffer().toString(); } catch (Exception e) { throw new IOException(e); } } }