package com.mqp.doc2xml; import java.io.File; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Text; /** * * 将配置中的数据保存在本地XML文件中 * * @author Administrator * */ // 使用Dom方式来保存数据 public class Doc2Xml { public static boolean saveParam2Xml(String ip_value, String socket_value) { // 文档生成器工厂 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // 实例化文档生成器 try { DocumentBuilder builder = factory.newDocumentBuilder(); // 生成一个文档 Document document = builder.newDocument(); // 创建XML文件所需的各种对象并序列化(元素) Element config = document.createElement("config");// 创建根节点 Element ip = document.createElement("ip");// 创建元素节点 Element socket = document.createElement("socket"); Text ip_text = document.createTextNode(ip_value);// 创建text Text socket_text = document.createTextNode(socket_value); ip.appendChild(ip_text); socket.appendChild(socket_text); config.appendChild(ip); config.appendChild(socket); document.appendChild(config);// 添加到文档中 // 调用方法,将文档写入xml文件中 return Doc2Xml.writeXml(document, "../Test/xml/text.xml"); } catch (ParserConfigurationException e) { e.printStackTrace(); return false; } } public static boolean writeXml(Document document, String filepath) { // 创建转化工厂 TransformerFactory factory = TransformerFactory.newInstance(); // 创建转换实例 try { Transformer transformer = factory.newTransformer(); // 将建立好的DOM放入DOM源中 DOMSource domSource = new DOMSource(document); // 创建输出流 StreamResult result = new StreamResult(new File(filepath)); // 开始转换 transformer.transform(domSource, result); return true; } catch (TransformerConfigurationException e) { e.printStackTrace(); return false; } catch (TransformerException e) { e.printStackTrace(); return false; } } public static void main(String[] args) { System.out.println(Doc2Xml.saveParam2Xml("10.1.23.2", "8888") + "----------"); } }