public class XmlStringer {
public XmlStringer() {
builder=new StringBuilder();
}
private StringBuilder builder;
public XmlStringer startNode(String name){
builder.append("<"+name+">");
return this;
}
public XmlStringer endNode(String name){
builder.append("</"+name+">");
return this;
}
public XmlStringer attribute(String name,String value){
builder.replace(builder.length()-1, builder.length(), " "+name+"='"+value+"'>");
return this;
}
public XmlStringer attribute(String name,int value){
builder.replace(builder.length()-1, builder.length(), " "+name+"='"+value+"'>");
return this;
}
public XmlStringer text(String text){
builder.append(text);
return this;
}
public XmlStringer text(int text){
builder.append(text);
return this;
}
public XmlStringer text(boolean text){
builder.append(text);
return this;
}
public XmlStringer text(byte[] data) {
builder.append(new String(data));
return this;
}
public void clear(){
builder.delete(0, builder.length());
}
@Override
public String toString() {
return builder.toString();
}
}
用法:
public static void main(String[] args) {
XmlStringer stringer=new XmlStringer();
stringer.startNode("tobacco");
stringer.attribute("action", "tasksave");
stringer.attribute("taskid", "000000000018878");
stringer.startNode("taskstatus");
stringer.text("2");
stringer.endNode("taskstatus");
stringer.startNode("subtask");
stringer.attribute("subtaskid", "77777777777");
stringer.attribute("subtaskstatus", "9");
stringer.attribute("type", "m2_0");
stringer.startNode("biaozhun");
stringer.startNode("appraise");
stringer.startNode("selected_index");
stringer.text("0");
stringer.endNode("selected_index");
stringer.startNode("comment");
stringer.text(1);
stringer.endNode("comment");
stringer.endNode("appraise");
stringer.endNode("biaozhun");
stringer.endNode("subtask");
stringer.endNode("tobacco");
System.out.println(stringer.toString());
}