使用jdom创建xml文本并格式化输出为字符串xml

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.Namespace;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

public class GeneralXML {

	public static void main(String[] args) throws IOException {
		//最终生成输出的xml
		String xml = "<beans   "
				+ "xmlns=\"http://www.springframework.org/schema/beans\"    "
				+ "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"   "
				+ "xsi:schemaLocation=\"http://www.springframework.org/schema/beans   http://www.springframework.org/schema/beans/spring-beans.xsd\"> "
				+ "version=\"1.0\""
				+ "<bean id=\"user\" class=\"cn.zlz.User\"> "
				+ "<property name=\"sexs\">男</property>" + "</bean>"
				+ "</beans>  ";
//		System.out.println(xml);
		Element root = new Element("beans");
		Document doc = new Document(root);
		//添加第一个声明
		Namespace ns = Namespace.getNamespace("","http://www.w3.org/2001/XMLSchema-instance");
		//这里使用setNamespace
		root.setNamespace(ns);
		//添加第二个声明,xsi,第三个的时候需要用
		Namespace ns1 = Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
		root.addNamespaceDeclaration(ns1);
		//添加 si:schemaLocation 需要使用第二个声明
		root.setAttribute(new Attribute(
				"schemaLocation",
				"http://www.springframework.org/schema/beans   http://www.springframework.org/schema/beans/spring-beans.xsd",
				ns1));
		//添加属性
		root.setAttribute("version", "1.0");
		//创建下级节点
		Element bean = new Element("bean");
		bean.setAttribute("id", "user");
		bean.setAttribute("class", "cn.zlz.User");
		//这里再添加一次声明,不知道为什么不添加这句,会使root的子节点都会有一个 xlmns = ""的属性。
		bean.setNamespace(ns);
		
		Element property = new Element("property");
		property.setAttribute("name", "sexs");
		//添加属性节点
		property.setText("男");
		Element bean1 = new Element("bean1");
		bean1.setNamespace(ns);
		//将节点添加到父节点
		bean.addContent(property);
		root.addContent(bean);
		root.addContent(bean1);
		
		//格式化输出xml文件字符串
		Format format = Format.getCompactFormat();
		format.setEncoding("utf-8");
		//这行保证输出后的xml的格式
		format.setIndent(" ");
		XMLOutputter xmlout = new XMLOutputter(format);
		ByteArrayOutputStream byteRsp = new ByteArrayOutputStream();
		xmlout.output(doc, byteRsp);
		String str = byteRsp.toString("utf-8");
		System.out.println(str);
	}
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值