亲宝软件园·资讯

展开

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

cat_book_milk 人气:0

如下所示:

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并转为字符串的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

加载全部内容

相关教程
猜你喜欢
用户评论