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

时间:2021-05-19

如下所示:

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

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章