欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

Java生成xml

时间:2023-07-02
1.创建document

documentBuilderFactory factory = documentBuilderFactory.newInstance();documentBuilder db = factory.newdocumentBuilder();document document = db.newdocument();document.setXmlStandalone(false); // 去掉xml 的默认文件头

2.创建节点并放入值

Element include = document.createElement("include");Element gateway = document.createElement("gateway");Element param = document.createElement("param");Element param1 = document.createElement("param");Element param2 = document.createElement("param");Element param3 = document.createElement("param");gateway.setAttribute("name",name);

3.添加节点层级

gateway.setAttribute("name",sipGateway);include.appendChild(gateway);param.setAttribute("name","username");param1.setAttribute("name","realm");param2.setAttribute("name","proxy");param3.setAttribute("name","register");param.setAttribute("value",callNumber);param1.setAttribute("value",realm);param2.setAttribute("value",proxy);param3.setAttribute("value",register);gateway.appendChild(param);gateway.appendChild(param1);gateway.appendChild(param2);gateway.appendChild(param3);document.appendChild(include);

4.设置换行并输出

// 创建TransformerFactory对象 TransformerFactory tff = TransformerFactory.newInstance(); // 创建 Transformer对象 Transformer tf = tff.newTransformer(); // 输出内容是否使用换行 tf.setOutputProperty(OutputKeys.INDENT, "yes"); //缩进2格 tf.setOutputProperty(OutputPropertiesFactory.S_KEY_INDENT_AMOUNT, "2"); tf.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"yes"); StreamResult result = new StreamResult(out) ; tf.transform(new DOMSource(document.getdocumentElement()), new StreamResult(out));

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。