本人不善言谈,直接贴出代码,希望给有需要的朋友一些帮助。
import java.io.ByteArrayOutputStream; import java.io.FileOutputStream; import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; 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; public class OperationXmlFile { public static Document createDocument() { try { DocumentBuilderFactory factory = DocumentBuilderFactory .newInstance(); DocumentBuilder builder; builder = factory.newDocumentBuilder(); return builder.newDocument(); } catch (ParserConfigurationException e) { e.printStackTrace(); return null; } } public static Element addChildElement(Element parentElement, String elementName, String nodeValue, Document document) { Element el = document.createElement(elementName); el.appendChild(document.createTextNode(nodeValue)); if (parentElement != null) parentElement.appendChild(el); else document.appendChild(el); return el; } public static void addAttribute(Element element, String propetyName, String propertyValue) { element.setAttribute(propetyName, propertyValue); } public static void toSave(Document document, String filePath) { try { TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); DOMSource source = new DOMSource(document); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); ByteArrayOutputStream buf = new ByteArrayOutputStream(); StreamResult result = new StreamResult(buf); transformer.transform(source, result); FileOutputStream file = new FileOutputStream(filePath); file.write(buf.toByteArray()); transformer.transform(source, result); } catch (TransformerException mye) { mye.printStackTrace(); } catch (IOException exp) { exp.printStackTrace(); } } public static void main(String[] args) { Document document = createDocument(); Element el = OperationXmlFile.addChildElement(null, "hehe", "", document); Element elchi = OperationXmlFile.addChildElement(el, "haha", "", document); OperationXmlFile.addChildElement(elchi, "haha", "ggg", document); OperationXmlFile.addChildElement(el, "haha2", "haha2", document); OperationXmlFile.toSave(document, "E:/aa.xml"); } }