Details
-
Wish
-
Status: Closed
-
Major
-
Resolution: Fixed
-
1.0-beta-10
-
None
-
All
Description
Till beta 10, we can only use groovy.util.NodePrinter to print a note, but we can not output it in xml format. Maybe we should print it out in xml format.
Below is the every simple implementation for it.
import groovy.xml.*;
import groovy.util.*;
import java.io.*;
import java.util.*;
class XmlNodePrinter {
out = new IndentPrinter(new PrintWriter(new OutputStreamWriter(System.out)));
private String getWritableString(String source) {
StringBuffer buf = new StringBuffer();
for (c in source) {
switch (c)
{ case '&' : buf.append("&"); //$NON-NLS-1$ break; case '<' : buf.append("<"); //$NON-NLS-1$ break; case '>' : buf.append(">"); //$NON-NLS-1$ break; //case '\'' : // buf.append("'"); //$NON-NLS-1$ // break; //case '\"' : // buf.append("""); //$NON-NLS-1$ // break; default : buf.append(c); break; } }
return buf.toString();
}
protected String writeShallow(Node node, boolean terminate) {
String sep = System.getProperty("line.separator"); //$NON-NLS-1$
StringBuffer buffer = new StringBuffer("<" + node.name()); //$NON-NLS-1$
attrs = new ArrayList(node.attributes().entrySet());
if (attrs.size() == 1) {
if (attrs[0].getValue().length() > 0)
} else {
for (each in attrs)
}
if (terminate)
buffer.append("/"); //$NON-NLS-1$
buffer.append(">"); //$NON-NLS-1$
return buffer.toString();
}
private String getAttribute(Map.Entry entry)
{ return entry.getKey() + "=\"" + entry.getValue() + "\""; } public String write(Node node) {
String sep = System.getProperty("line.separator"); //$NON-NLS-1$
StringBuffer buffer = new StringBuffer();
Object value = node.value();
if (value instanceof List && value.size() > 0) {
buffer.append(writeShallow(node, false) + sep);
for (each in value)
{ indentLevel = indentLevel + 1; buffer.append(getIndent() + write(each) + sep); indentLevel = indentLevel - 1; }buffer.append(getIndent() + "</" + node.name() + ">"); //$NON-NLS-1$ //$NON-NLS-2$
} else if (value instanceof String && value.length() > 0) {
buffer.append(writeShallow(node, false));
if (value.length() < 80 )
else
{ buffer.append(sep + getIndent() + " " + getWritableString(value)); //$NON-NLS-1$ buffer.append(sep + getIndent() + "</" + node.name() + ">"); //$NON-NLS-1$ //$NON-NLS-2$ }} else
{ buffer.append(writeShallow(node, true)); } return buffer.toString();
}
// user can custom the indent.
public void setIndent(String indent) {
}
public String getIndent()
{ // default using 4 whitespace s = " " * indentLevel; return s; } private int indentLevel = 0;
}
Attachments
Issue Links
- is duplicated by
-
GROOVY-940 factor out groovy.util.XmlTemplateEngine.XmlPrinter as stand-alone class
- Closed
- is related to
-
GROOVY-839 Adding valid xml start and end tags for groovy template scripts
- Closed