(一)新建一个xml文件,然后往里面添加元素
package com.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.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.*; import org.xml.sax.SAXException; public class Writer { private Document doc; private Element root; public void parseDocAndCreateFile(){ try { DocumentBuilderFactory dFac=DocumentBuilderFactory.newInstance(); DocumentBuilder dBud=dFac.newDocumentBuilder(); // this.doc=dBud.parse(this.f); doc=dBud.newDocument(); } catch (ParserConfigurationException e) { // TODO 自动生成 catch 块 e.printStackTrace(); } } public void initDoc(){ this.root=doc.createElement("musiclession"); this.doc.appendChild(this.root); } // public void saveDoc(){ // this.doc.appendChild(this.root); // } public void writeStu(String id,String name ,int age,int score){ Element eStu=doc.createElement("student"); Element eName=doc.createElement("name"); eName.appendChild(doc.createTextNode(name)); Attr aId=doc.createAttribute("ID"); aId.appendChild(doc.createTextNode(id)); Element eAge=doc.createElement("age"); eAge.appendChild(doc.createTextNode(String.valueOf(age))); Element eScore=doc.createElement("score"); eScore.appendChild(doc.createTextNode(String.valueOf(score))); eStu.setAttributeNode(aId); eStu.appendChild(eName); eStu.appendChild(eAge); eStu.appendChild(eScore); System.out.println("ok"); this.root.appendChild(eStu); } // public void printDoc(){ // Element e=doc.getDocumentElement(); // System.out.println(e.getTagName()); // } public void saveDoc(String filename){ File f=new File(filename); try { TransformerFactory tfFac=TransformerFactory.newInstance(); Transformer tf=tfFac.newTransformer(); //要使用 tf.transform(source, result)方法 StreamResult result=new StreamResult(f); DOMSource source=new DOMSource(this.doc); tf.setOutputProperty(OutputKeys.VERSION, "1.0"); tf.setOutputProperty(OutputKeys.ENCODING, "gb2312"); tf.setOutputProperty(OutputKeys.INDENT, "yes"); tf.transform(source, result); } catch (TransformerConfigurationException e) { // TODO 自动生成 catch 块 e.printStackTrace(); } catch (TransformerException e) { // TODO 自动生成 catch 块 e.printStackTrace(); } } public static void main(String [] args){ Writer w=new Writer(); w.parseDocAndCreateFile(); w.initDoc(); w.writeStu("s101","李华" , 12, 92); w.writeStu("s102", "笑林", 22, 82); w.writeStu("s103", "王明", 18, 90); //w.writeStu("11111", "11111", 18, 90); //w.saveDoc(); //w.printDoc(); w.saveDoc("F://testDoc//DOM4XML//student.xml"); } }
(二)读取一个已有xml,修改元素的值和添加新元素
package com.util; import java.io.File; import java.io.IOException; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.TransformerFactory; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.*; import org.xml.sax.SAXException; public class DOMConvert { public static void main(String[] args) { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse("F://testDoc//DOM4XML//students.xml"); Element eltStu = doc.createElement("student"); Element eltName = doc.createElement("name"); Element eltAge = doc.createElement("age"); Attr attr = doc.createAttribute("sn"); attr.setValue("03"); Text txtName = doc.createTextNode("王五"); Text txtAge = doc.createTextNode("19"); eltName.appendChild(txtName); eltAge.appendChild(txtAge); eltStu.appendChild(eltName); eltStu.appendChild(eltAge); eltStu.setAttributeNode(attr); Element eltRoot = doc.getDocumentElement(); //新增元素 eltRoot.appendChild(eltStu); NodeList nl = doc.getElementsByTagName("student"); // Node nodeDel=(Element)nl.item(0); // nodeDel.getParentNode().removeChild(nodeDel); //修改某个元素的值 Element eltChg = (Element) nl.item(0); Node nodeAgeChg = eltChg.getElementsByTagName("age").item(0); nodeAgeChg.getFirstChild().setNodeValue("22"); // 利用文档节点创建一个DOM输入源 DOMSource source = new DOMSource(doc); // new File一个文件构造一个StreamResult对象,用于保存转换后结果。这里File为原来的文件,即实现了修改原xml文件的功能。 StreamResult result = new StreamResult(new File("F://testDoc//DOM4XML//students.xml")); // 得到转换器工厂类的实例 TransformerFactory tff = TransformerFactory.newInstance(); // 创建一个新的转换器,用于执行恒等转换, // 即直接将DOM输入源的内容复制到结果文档中。 Transformer tf = tff.newTransformer(); tf.setOutputProperty(OutputKeys.VERSION, "1.0"); tf.setOutputProperty(OutputKeys.ENCODING, "gb2312"); tf.setOutputProperty(OutputKeys.INDENT, "yes"); // 执行转换 tf.transform(source, result); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (TransformerConfigurationException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } } }
对xml文件修改后关键是用转换器进行修改:
try{ // 利用文档节点创建一个DOM输入源 DOMSource source = new DOMSource(doc); // new File一个文件构造一个StreamResult对象,用于保存转换后结果。这里File为原来的文件,即实现了修改原xml文件的功能。 StreamResult result = new StreamResult(new File("F://testDoc//DOM4XML//students.xml")); // 得到转换器工厂类的实例 TransformerFactory tff = TransformerFactory.newInstance(); // 创建一个新的转换器,用于执行恒等转换, // 即直接将DOM输入源的内容复制到结果文档中。 Transformer tf = tff.newTransformer(); tf.setOutputProperty(OutputKeys.VERSION, "1.0"); tf.setOutputProperty(OutputKeys.ENCODING, "gb2312"); tf.setOutputProperty(OutputKeys.INDENT, "yes"); // 执行转换 tf.transform(source, result); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (TransformerConfigurationException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); }
(三)对xml进行parse时,文件名不能有空格或中文,否则报错如下:
java.net.MalformedURLException: unknown protocol: d
at java.net.URL.<init>(URL.java:574)
at java.net.URL.<init>(URL.java:464)
at java.net.URL.<init>(URL.java:413)
at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.setupCurrentEntity(XMLEntityManager.java:650)
at com.sun.org.apache.xerces.internal.impl.XMLVersionDetector.determineDocVersion(XMLVersionDetector.java:186)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:771)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:737)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:107)
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:225)
at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:283)
at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:180)
at com.util.testDOMQuestion.writeXML(testDOMQuestion.java:51)
at com.util.testDOMQuestion.main(testDOMQuestion.java:111)
解决方法:用File类表示文件!
DocumentBuilder db = dbf.newDocumentBuilder();
File file = new File(fileaddr);
Document doc = db.parse(file);