java怎么写xml文件的单标签
怎么用java写xml的封闭标签啊??如:<inputid="1"/>在线等待。。双标签我会。。。。。。谢谢...
怎么用java写xml的封闭标签啊 ??如:<input id="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<String, Object> props;
public ElementBuilder(String name) {
this(name, null);
}
public ElementBuilder(String name, Map<String, Object> props) {
this.name = name;
this.props = new LinkedHashMap<String, Object>();
if (props != null) {
for (Entry<String, Object> 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<String, Object> 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);
}
输出示例
<input id="1" />
<input id="1"></input>
<input type="text" name="user" />
用法说明
构造函数,name是标签名
setProp,name是属性名,value是属性值
setBody,body是标签体内容,如果不调用或为null,就是封闭标签。
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询