dom读写xml
package com.xml; import java.io.File; import java.io.IOException; import javax.xml.crypto.dsig.Transform; 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.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.xml.sax.SAXException; public class DOM { public static void dom_read() { DocumentBuilderFactory d=DocumentBuilderFactory.newInstance(); try { DocumentBuilder bu=d.newDocumentBuilder(); Document dom=bu.parse("pom1.xml"); NodeList nl=dom.getElementsByTagName("dependency"); System.out.println(nl.getLength()); for(int i=0;i<nl.getLength();i++) { Node node=nl.item(i); NodeList nnm=node.getChildNodes(); for(int k=0;k<nnm.getLength();k++) { Node node1=nnm.item(k); if(node1.getNodeType()==Node.ELEMENT_NODE) { String tt=node1.getNodeName(); String tt1=node1.getTextContent(); System.out.println(tt+":"+tt1+"\n"); } } } } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void dom_write() throws TransformerConfigurationException { DocumentBuilderFactory d=DocumentBuilderFactory.newInstance(); try { DocumentBuilder bu=d.newDocumentBuilder(); Document Document = bu.newDocument(); // Document.setXmlStandalone(true); Element eleroot=Document.createElement("books"); Element elebook=Document.createElement("book"); Element bookname=Document.createElement("name"); bookname.setTextContent("xiaowangzi"); elebook.setAttribute("id", "1"); elebook.appendChild(bookname); eleroot.appendChild(elebook); Document.appendChild(eleroot); TransformerFactory tf=TransformerFactory.newInstance(); try { Transformer t=tf.newTransformer(); t.setOutputProperty(OutputKeys.INDENT, "yes"); t.transform(new DOMSource(Document), new StreamResult(new File("books1.xml"))); } catch (TransformerException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void main(String[] args) throws TransformerConfigurationException { dom_read(); dom_write(); } }