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));