XML- 解析
XML解析的分式分为两种,DOM和SAX。
DOM(Document Object Model,即文挡对象模型)是W3C组织推荐的解析XML的一种方式。DOM解析的缺点是文挡太大的话,内存消耗大,速度慢。但对DOM进行增删查改很方便。
SAX是一个用于处理XML事件驱动的“推”模型,虽然它不是W3C标准,但它却是一个得到了广泛认可的API。SAX解析器不像DOM那样建立一个完整的文档树,而是在读取文档时激活一系列事件,这些事件被推给事件处理器,然后由事件处理器提供对文档内容的访问。SAX不会产生内存消耗大,但不能对数据进行增删改,只能对数据进行数据的读取。
XML解析开发包:JAXP(SUN),DOM4J
JAXP开发包是J2SE的一部份,它由JAVA.XML、ORG.W3C.DOM、ORG.XML.SAX包及其子包组成。在JAVA.XML.PARSERS包中,定义了几个工厂类,程序员调用这些工厂类,可以得到XML文挡的DOM或SAX的解析器,从而实现对XML文挡的解析。在JAVA.XML.PARSERS包中DocumentBuilderFactory用于创建DOM模式的解析器对象,DocumentBuilderFactory是一个抽象工厂类,不能直接实例好。该类提供了一个newInstance方法用于创建一个工厂对象。
使用JAXP创建一个XML解析文挡
View Code
import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; public class demo1 { public static void main(String[] args) throws Exception { //创建工厂 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); //得到DOM解析器 DocumentBuilder builder = factory.newDocumentBuilder(); //解析XML文挡 Document document = builder.parse("src/book.xml"); } }
使用JAXP对XML进行查操作
View Code
import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.junit.Test; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class demo1 { public static void main(String[] args) throws Exception { // 创建工厂 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // 得到DOM解析器 DocumentBuilder builder = factory.newDocumentBuilder(); // 解析XML文挡 Document document = builder.parse("src/book.xml"); } @Test public void read() throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse("src/book.xml"); NodeList list = document.getElementsByTagName("书名"); Node node = list.item(0); String content = node.getTextContent(); System.out.println(content); } //递归的例子 @Test public void read2() throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse("src/book.xml"); // 得到根结点 Node root = document.getElementsByTagName("书架").item(0); list(root); } private void list(Node node) { if(node instanceof org.w3c.dom.Element){ System.out.println(node.getNodeName()); } NodeList list = node.getChildNodes(); for(int i=0;i<list.getLength();i++){ Node child = list.item(i); list(child); } } //得到XML文档中的标签属性 @Test public void read3() throws Exception{ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document dom = builder.parse("src/book.xml"); Element node = (Element)dom.getElementsByTagName("书架").item(0); String value = node.getAttribute("电话"); System.out.println(value); } }
使用JAXP对XML文挡进行增删改
import java.io.FileOutputStream; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.junit.Test; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class demo1 { @Test public void add() throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document dom = builder.parse("src/book.xml"); //创建节点 Element price = dom.createElement("价格"); price.setTextContent("100"); //把节点加到第一本书上 Element book = (Element)dom.getElementsByTagName("书").item(0); book.appendChild(price); //把更新后的内容从内存中写回XML文挡里 TransformerFactory tffactory = TransformerFactory.newInstance(); Transformer tf = tffactory.newTransformer(); tf.transform(new DOMSource(dom), new StreamResult(new FileOutputStream("src/book.xml"))); } //往指定的位置前插入节点 @Test public void add2() throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document dom = builder.parse("src/book.xml"); //创建节点 Element price = dom.createElement("价格"); price.setTextContent("100"); //得到参考节点 Element refNode = (Element)dom.getElementsByTagName("作者").item(0); //往指定的位置前插入节点 Element book = (Element)dom.getElementsByTagName("书").item(0); book.insertBefore(price, refNode); //把更新后的内容从内存中写回XML文挡里 TransformerFactory tffactory = TransformerFactory.newInstance(); Transformer tf = tffactory.newTransformer(); tf.transform(new DOMSource(dom), new StreamResult(new FileOutputStream("src/book.xml"))); } //往XML结点上添加属性 @Test public void addAttr() throws Exception{ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document dom = builder.parse("src/book.xml"); //添加属性 Element bookName = (Element)dom.getElementsByTagName("书名").item(0); bookName.setAttribute("name", "xxxx"); //把更新后的内容从内存中写回XML文挡里 TransformerFactory tffactory = TransformerFactory.newInstance(); Transformer tf = tffactory.newTransformer(); tf.transform(new DOMSource(dom), new StreamResult(new FileOutputStream("src/book.xml"))); } //删除 @Test public void delete() throws Exception{ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document dom = builder.parse("src/book.xml"); //得到要删除的结点 Element e = (Element)dom.getElementsByTagName("价格").item(0); //得到要删除结点的爸爸 Element book = (Element)dom.getElementsByTagName("书").item(0); //爸爸删除儿子 book.removeChild(e); //把更新后的内容从内存中写回XML文挡里 TransformerFactory tffactory = TransformerFactory.newInstance(); Transformer tf = tffactory.newTransformer(); tf.transform(new DOMSource(dom), new StreamResult(new FileOutputStream("src/book.xml"))); } //删除2 @Test public void delete2() throws Exception{ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document dom = builder.parse("src/book.xml"); //得到要删除的结点 Element e = (Element)dom.getElementsByTagName("价格").item(0); e.getParentNode().removeChild(e); //把更新后的内容从内存中写回XML文挡里 TransformerFactory tffactory = TransformerFactory.newInstance(); Transformer tf = tffactory.newTransformer(); tf.transform(new DOMSource(dom), new StreamResult(new FileOutputStream("src/book.xml"))); } //更新价格 @Test public void update() throws Exception{ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document dom = builder.parse("src/book.xml"); Element e = (Element)dom.getElementsByTagName("价格").item(0); e.setTextContent("100"); //把更新后的内容从内存中写回XML文挡里 TransformerFactory tffactory = TransformerFactory.newInstance(); Transformer tf = tffactory.newTransformer(); tf.transform(new DOMSource(dom), new StreamResult(new FileOutputStream("src/book.xml"))); } }
BOOK.XML
View Code
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <书架 电话="89891231"> <书> <书名 name="xxxx">C#程序设计</书名> <作者>Ketty</作者> <价格>100</价格> </书> <书> <书名>Java程序设计</书名> <作者>Okla</作者> <价格>77</价格> </书> </书架>
================================
一个踪合的例子
View Code
//EXAM.XML文件 //--------------------------------------------------------------- <?xml version="1.0" encoding="UTF-8" standalone="no"?> <exam> <student examid="222" idcard="111"> <name>张三</name> <location>汕头</location> <grade>89</grade> </student> <student examid="444" idcard="333"> <name>李四</name> <location>广州</location> <grade>67</grade> </student> <student examid="121"> <name>aaa</name> <location>北京</location> <grade>89</grade> </student> </exam> //--------------------------------------------------------------- //XMLUTILS文件 //--------------------------------------------------------------- import java.io.FileOutputStream; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; public class XmlUtils { private static String fileName = "src/exam.xml"; public static Document getDocument() throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document dom = builder.parse(fileName); return dom; } public static void writeXml(Document dom) throws Exception { // 把更新后的内容从内存中写回XML文挡里 TransformerFactory tffactory = TransformerFactory.newInstance(); Transformer tf = tffactory.newTransformer(); tf.transform(new DOMSource(dom), new StreamResult(new FileOutputStream( fileName))); } } //--------------------------------------------------------------- //Student.DAO文件 //--------------------------------------------------------------- import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; public class StudentDao { //增加 public void add(Student s) { try { Document dom = XmlUtils.getDocument(); // 创建出封装学生信息的标签 Element student_tag = dom.createElement("student"); student_tag.setAttribute("examid", s.getIdcard()); student_tag.setAttribute("examid", s.getExamid()); // 创建用于封装学生姓名,所在地和成绩的标签 Element name = dom.createElement("name"); Element location = dom.createElement("location"); Element grade = dom.createElement("grade"); name.setTextContent(s.getName()); location.setTextContent(s.getLocation()); grade.setTextContent(s.getGrade()); student_tag.appendChild(name); student_tag.appendChild(location); student_tag.appendChild(grade); dom.getElementsByTagName("exam").item(0).appendChild(student_tag); // 将结果保存 XmlUtils.writeXml(dom); } catch (Exception e) { e.printStackTrace(); } } //查找 public Student find(String examid) { try { Document dom = XmlUtils.getDocument(); NodeList list = dom.getElementsByTagName("student"); for (int i = 0; i < list.getLength(); i++) { Element student_tag = (Element) list.item(i); if (student_tag.getAttribute("examid") == examid) { Student s = new Student(); s.setExamid(examid); s.setIdcard(student_tag.getAttribute("idcard")); s.setName(student_tag.getElementsByTagName("name").item(0) .getTextContent()); s.setLocation(student_tag.getElementsByTagName("location") .item(0).getTextContent()); s.setGrade(student_tag.getElementsByTagName("grade") .item(0).getTextContent()); return s; } } } catch (Exception e) { e.printStackTrace(); } return null; } //删除 public boolean delete(String name){ try { Document dom = XmlUtils.getDocument(); NodeList list = dom.getElementsByTagName("name"); for(int i=0;i<list.getLength();i++){ if(list.item(i).getTextContent() == name){ //寻找爸爸删除儿子 list.item(i).getParentNode().getParentNode().removeChild(list.item(i).getParentNode()); XmlUtils.writeXml(dom); return true; } } } catch (Exception e) { e.printStackTrace(); } return false; } } //--------------------------------------------------------------- //Student文件 //--------------------------------------------------------------- public class Student { private String idcard; private String examid; private String name; private String location; private String grade; public String getIdcard() { return idcard; } public void setIdcard(String idcard) { this.idcard = idcard; } public String getExamid() { return examid; } public void setExamid(String examid) { this.examid = examid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getGrade() { return grade; } public void setGrade(String grade) { this.grade = grade; } } //--------------------------------------------------------------- //TestDemo文件 //--------------------------------------------------------------- import org.junit.Test; public class DemoTest { public static void main(String[] args) { } @Test public void testAdd() { StudentDao dao = new StudentDao(); Student s = new Student(); s.setExamid("121"); s.setGrade("89"); s.setIdcard("121"); s.setLocation("北京"); s.setName("aaa"); dao.add(s); } @Test public void testFind() { StudentDao dao = new StudentDao(); Student s = new Student(); s = dao.find("444"); System.out.println(s.getName()); } }