日期:2014-05-18 浏览次数:20806 次
package com.aowin.sms.util; import java.io.File; import java.io.IOException; 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.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Text; import org.xml.sax.SAXException; public class XmlFile { private DocumentBuilderFactory dbf = null; private DocumentBuilder db = null; private Document d = null; private File file = null; public XmlFile(String fileName) { this(new File(fileName)); } public XmlFile(File file) { try { dbf = DocumentBuilderFactory.newInstance(); db = dbf.newDocumentBuilder(); this.file = file; } catch (ParserConfigurationException e) { System.out.println(e.getMessage()); } } public void createRootElement(String name) { d = db.newDocument(); Element root = d.createElement(name); d.appendChild(root); write(); } public void appendElement(String tagname, String name) { appendElement(tagname, name, 0); } public void appendElement(String tagname, String name, int index){ try { d = db.parse(file); Element child = d.createElement(name); NodeList fe = d.getElementsByTagName(tagname); Node father = fe.item(index); father.appendChild(child); write(); } catch (SAXException e) { System.out.println(e.getMessage()); } catch (IOException e) { System.out.println(e.getMessage()); } } public void appendElement(String tagname, String name, String value, int index){ try { d = db.parse(file); NodeList fe =