欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java 生成xml并转为字符串的方法

程序员文章站 2024-02-13 15:17:22
如下所示: import javax.xml.parsers.documentbuilderfactory; import javax.xml.parsers....

如下所示:

import javax.xml.parsers.documentbuilderfactory;
import javax.xml.parsers.documentbuilder;
import javax.xml.transform.transformerfactory;
import javax.xml.transform.outputkeys;
import javax.xml.transform.transformer;
import javax.xml.transform.dom.domsource;
import javax.xml.transform.stream.streamresult;
 
import org.apache.commons.io.output.bytearrayoutputstream;
 
import org.w3c.dom.document;
import org.w3c.dom.element;
 
public class test {
	
	private string createxml() {
		string xmlstring = "";
 
		documentbuilderfactory factory = documentbuilderfactory.newinstance();
		try {
			documentbuilder builder = factory.newdocumentbuilder();
			document document = builder.newdocument();
			document.setxmlstandalone(true);
 
			element iteminfo = document.createelement("iteminfo");
			document.appendchild(iteminfo);
 
			element itemstatistics = document.createelement("itemstatistics");
			itemstatistics.settextcontent("商品统计");
			iteminfo.appendchild(itemstatistics);
 
			element items = document.createelement("items");
			iteminfo.appendchild(items);
			// 此处可以循环添加
			element item = document.createelement("item");
			items.appendchild(item);
 
			element itemname = document.createelement("itemname");
			itemname.settextcontent("iphone");
			item.appendchild(itemname);
 
			element itemnum = document.createelement("itemnum");
			itemnum.settextcontent("3");
			item.appendchild(itemnum);
 
			element itemvalue = document.createelement("itemvalue");
			itemvalue.settextcontent("1000000");
			item.appendchild(itemvalue);
 
			element remark = document.createelement("remark");
			remark.settextcontent("配送");
			iteminfo.appendchild(remark);
 
			transformerfactory transfactory = transformerfactory.newinstance();
			transformer transformer = transfactory.newtransformer();
			transformer.setoutputproperty(outputkeys.indent, "yes");
			domsource domsource = new domsource(document);
 
			// xml transform string
			bytearrayoutputstream bos = new bytearrayoutputstream();
			transformer.transform(domsource, new streamresult(bos));
			xmlstring = bos.tostring();
			system.out.println(xmlstring);
		} catch (exception e) {
			e.printstacktrace();
		}
 
		return xmlstring;
	}
}

结果:

<?xml version="1.0" encoding="utf-8"?>
<iteminfo>
<itemstatistics>商品统计</itemstatistics>
<items>
<item>
<itemname>iphone</itemname>
<itemnum>3</itemnum>
<itemvalue>1000000</itemvalue>
</item>
</items>
<remark>配送</remark>
</iteminfo>

去掉头文件

<?xml version="1.0" encoding="utf-8"?>

的办法暂时只能想到:

xmlstring.substring(38)

以上这篇java 生成xml并转为字符串的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。