java xml 单标签_java怎么写xml文件的单标签

展开全部

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) {

32313133353236313431303231363533e78988e69d8331333335333731this(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,就是封闭标签。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值