java/parameter-lister/src/info/glogalcode/parameterLister/modules/XmlModule.java
author František Kučera <franta-hg@frantovo.cz>
Sat, 10 Sep 2016 23:22:29 +0200
changeset 23 4ad40aaed4bb
parent 22 91e52083f255
child 28 bfef9f34e438
permissions -rw-r--r--
java: simple XML output module
franta-hg@21
     1
package info.glogalcode.parameterLister.modules;
franta-hg@21
     2
franta-hg@21
     3
import info.glogalcode.parameterLister.OutputModule;
franta-hg@21
     4
import info.glogalcode.parameterLister.OutputModuleException;
franta-hg@21
     5
import java.io.OutputStream;
franta-hg@21
     6
import java.io.PrintWriter;
franta-hg@21
     7
import java.util.List;
franta-hg@21
     8
franta-hg@21
     9
/**
franta-hg@23
    10
 * Just a simple XML output.
franta-hg@23
    11
 * For more complex documents, use {@linkplain javax.xml.stream.XMLStreamWriter}
franta-hg@21
    12
 *
franta-hg@21
    13
 * @author Ing. František Kučera (frantovo.cz)
franta-hg@21
    14
 */
franta-hg@22
    15
public class XmlModule implements OutputModule {
franta-hg@21
    16
franta-hg@21
    17
	@Override
franta-hg@21
    18
	public void process(OutputStream output, List<String> parameters) throws OutputModuleException {
franta-hg@21
    19
		try (PrintWriter out = new PrintWriter(output)) {
franta-hg@23
    20
			out.println("<parameters>");
franta-hg@21
    21
			for (String parameter : parameters) {
franta-hg@23
    22
				out.print("\t<parameter>");
franta-hg@23
    23
				out.print(escapeXmlText(parameter));
franta-hg@23
    24
				out.println("</parameter>");
franta-hg@21
    25
				out.flush();
franta-hg@21
    26
			}
franta-hg@23
    27
			out.println("</parameters>");
franta-hg@21
    28
		}
franta-hg@21
    29
	}
franta-hg@21
    30
franta-hg@23
    31
	/**
franta-hg@23
    32
	 * @param s original text
franta-hg@23
    33
	 * @return escaped text that can be safely concatenated between two XML tags (not safe for
franta-hg@23
    34
	 * attribute
franta-hg@23
    35
	 * values)
franta-hg@23
    36
	 */
franta-hg@23
    37
	private static String escapeXmlText(String s) {
franta-hg@23
    38
		return s.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
franta-hg@23
    39
	}
franta-hg@21
    40
}