Java教程

Java生成xml

本文主要是介绍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的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!