Java生成xml
2022/2/7 17:16:33
本文主要是介绍Java生成xml,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
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));
这篇关于Java生成xml的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-12-21《鸿蒙HarmonyOS应用开发从入门到精通(第2版)》简介
- 2024-12-21后台管理系统开发教程:新手入门全指南
- 2024-12-21后台开发教程:新手入门及实战指南
- 2024-12-21后台综合解决方案教程:新手入门指南
- 2024-12-21接口模块封装教程:新手必备指南
- 2024-12-21请求动作封装教程:新手必看指南
- 2024-12-21RBAC的权限教程:从入门到实践
- 2024-12-21登录鉴权实战:新手入门教程
- 2024-12-21动态权限实战入门指南
- 2024-12-21功能权限实战:新手入门指南