java 生成xml并转为字符串的方法
如下所示:
importjavax.xml.parsers.DocumentBuilderFactory; importjavax.xml.parsers.DocumentBuilder; importjavax.xml.transform.TransformerFactory; importjavax.xml.transform.OutputKeys; importjavax.xml.transform.Transformer; importjavax.xml.transform.dom.DOMSource; importjavax.xml.transform.stream.StreamResult; importorg.apache.commons.io.output.ByteArrayOutputStream; importorg.w3c.dom.Document; importorg.w3c.dom.Element; publicclasstest{ privateStringcreateXml(){ StringxmlString=""; DocumentBuilderFactoryfactory=DocumentBuilderFactory.newInstance(); try{ DocumentBuilderbuilder=factory.newDocumentBuilder(); Documentdocument=builder.newDocument(); document.setXmlStandalone(true); ElementitemInfo=document.createElement("ItemInfo"); document.appendChild(itemInfo); ElementitemStatistics=document.createElement("ItemStatistics"); itemStatistics.setTextContent("商品统计"); itemInfo.appendChild(itemStatistics); Elementitems=document.createElement("Items"); itemInfo.appendChild(items); //此处可以循环添加 Elementitem=document.createElement("Item"); items.appendChild(item); ElementitemName=document.createElement("ItemName"); itemName.setTextContent("iPhone"); item.appendChild(itemName); ElementitemNum=document.createElement("ItemNum"); itemNum.setTextContent("3"); item.appendChild(itemNum); ElementitemValue=document.createElement("ItemValue"); itemValue.setTextContent("1000000"); item.appendChild(itemValue); Elementremark=document.createElement("Remark"); remark.setTextContent("配送"); itemInfo.appendChild(remark); TransformerFactorytransFactory=TransformerFactory.newInstance(); Transformertransformer=transFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT,"yes"); DOMSourcedomSource=newDOMSource(document); //xmltransformString ByteArrayOutputStreambos=newByteArrayOutputStream(); transformer.transform(domSource,newStreamResult(bos)); xmlString=bos.toString(); System.out.println(xmlString); }catch(Exceptione){ e.printStackTrace(); } returnxmlString; } }
结果:
商品统计 iPhone 3 1000000 配送
去掉头文件
的办法暂时只能想到:
xmlString.substring(38)
以上这篇java生成xml并转为字符串的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。