java怎么写xml文件的单标签

2025-04-14 20:06:58
推荐回答(1个)
回答1:

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;

public class ElementBuilder {
private static final String QUOTE = "\"";

private String name;
private String body;
private Map props;

public ElementBuilder(String name) {
this(name, null);
}

public ElementBuilder(String name, Map props) {
this.name = name;
this.props = new LinkedHashMap();
if (props != null) {
for (Entry entry : props.entrySet()) {
setProp(entry.getKey(), entry.getValue());
}
}
}

public final ElementBuilder setProp(String name, Object value) {
if (name == null || name.length() == 0) {
throw new IllegalArgumentException("name is black");
}
if (value == null) {
throw new IllegalArgumentException("value is null");
}
props.put(name, value);
return this;
}

public final ElementBuilder setBody(String body) {
this.body = body;
return this;
}

public final String toString() {
StringBuilder builder = new StringBuilder();
builder.append("<");
builder.append(name);
for (Entry entry : props.entrySet()) {
builder.append(" ");
builder.append(entry.getKey());
builder.append("=");
builder.append(QUOTE);
builder.append(entry.getValue());
builder.append(QUOTE);
}
if (body == null) {
builder.append(" />");
} else {
builder.append(">");
builder.append(body);
builder.append(" builder.append(name);
builder.append(">");
}
return builder.toString();
}
}

演示用例

public static void main(String[] args) {
String element;

element = new ElementBuilder("input")
.setProp("id", "1")
.toString();
System.out.println(element);

element = new ElementBuilder("input")
.setProp("id", "1")
.setBody("")
.toString();
System.out.println(element);

element = new ElementBuilder("input")
.setProp("type", "text")
.setProp("name", "user")
.toString();
System.out.println(element);
}

输出示例



用法说明

构造函数,name是标签名

setProp,name是属性名,value是属性值

setBody,body是标签体内容,如果不调用或为null,就是封闭标签。