XML的jaxp版DOM解析 和SAX解析

import java.io.File; 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 Demo2 { //读取:<书名>Java就业培训教程</书名> 标签里面的值 @Test public void read1() throws Exception{ //1.创建解析器工厂 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); //2.创建dom解析器 DocumentBuilder builder = factory.newDocumentBuilder(); //3.解析xml文档 Document document = builder.parse(new File("src/book.xml")); NodeList list = document.getElementsByTagName("书名"); Node node = list.item(0); String content = node.getTextContent(); System.out.println(content); } //<书名 name="xxxx">Java就业培训教程</书名> 读取属性值 @Test public void read2() throws Exception{ //1.创建解析器工厂 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); //2.创建dom解析器 DocumentBuilder builder = factory.newDocumentBuilder(); //3.解析xml文档 Document document = builder.parse(new File("src/book.xml")); NodeList list = document.getElementsByTagName("书名"); Node node = list.item(0); Element e = (Element) node; String name = e.getAttribute("name"); System.out.println(name); } //递归出xml文档中的所有节点 @Test public void read3() throws Exception{ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(new File("src/book.xml")); Node node = document.getElementsByTagName("书架").item(0); list(node); } public void list(Node node){ if(node instanceof 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文档中插入:<售价>59.00元</售价> @Test public void insert() throws Exception{ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(new File("src/book.xml")); Node book = document.getElementsByTagName("书").item(0); //创建要添加的节点 Element e = document.createElement("售价"); e.setTextContent("59.00元"); book.appendChild(e); TransformerFactory tfactory = TransformerFactory.newInstance(); Transformer tf = tfactory.newTransformer(); tf.transform(new DOMSource(document), new StreamResult("src/book.xml")); } //向xml文档中指定位置插入:<售价>59.00元</售价> @Test public void insert2() throws Exception{ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(new File("src/book.xml")); Node book = document.getElementsByTagName("书").item(0); //创建要添加的节点 Element e = document.createElement("售价"); e.setTextContent("59.00元"); book.insertBefore(e, document.getElementsByTagName("售价").item(0)); //在此之前插入 TransformerFactory tfactory = TransformerFactory.newInstance(); Transformer tf = tfactory.newTransformer(); tf.transform(new DOMSource(document), new StreamResult("src/book.xml")); } //向xml文档节点插入属性: @Test public void insert3() throws Exception{ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(new File("src/book.xml")); //为书节点添加一个name属性 Node book = document.getElementsByTagName("书").item(0); Element e = (Element)book; e.setAttribute("name", "xxxxxxx"); TransformerFactory tfactory = TransformerFactory.newInstance(); Transformer tf = tfactory.newTransformer(); tf.transform(new DOMSource(document), new StreamResult("src/book.xml")); } //删除节点:<售价>59.00元</售价> @Test public void delete() throws Exception{ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(new File("src/book.xml")); //得到要删除节点的父节点 Node book = document.getElementsByTagName("书").item(0); //得到要删除的节点 Node price = document.getElementsByTagName("售价").item(0); book.removeChild(price); TransformerFactory tfactory = TransformerFactory.newInstance(); Transformer tf = tfactory.newTransformer(); tf.transform(new DOMSource(document), new StreamResult("src/book.xml")); } //删除节点:<售价>59.00元</售价> @Test public void delete1() throws Exception{ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(new File("src/book.xml")); //得到要删除的节点 Node price = document.getElementsByTagName("售价").item(0); //price.getParentNode().removeChild(price); price.getParentNode().getParentNode().getParentNode().removeChild(price.getParentNode().getParentNode()); TransformerFactory tfactory = TransformerFactory.newInstance(); Transformer tf = tfactory.newTransformer(); tf.transform(new DOMSource(document), new StreamResult("src/book.xml")); } //修改节点的值:<作者>xx</作者> 改为 zz @Test public void update() throws Exception{ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(new File("src/book.xml")); document.getElementsByTagName("作者").item(0).setTextContent("zz"); TransformerFactory tfactory = TransformerFactory.newInstance(); Transformer tf = tfactory.newTransformer(); tf.transform(new DOMSource(document), new StreamResult("src/book.xml")); } }  

--------------------------------------------------------------------------------

sax解析:

1.

public class Book { private String name; private String author; private String price; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } }  

 

<?xml version="1.0" encoding="UTF-8"?> <书架> <书> <书名 name="xxx">Java就业培训教程</书名> <作者>老黎</作者> <售价>59.00元</售价> <售价>109元</售价> <售价>59.00元</售价> </书> <书> <书名>JavaScript网页开发</书名> <作者>老刘</作者> <售价>28.00元</售价> </书> </书架>  

 

2.

import java.io.IOException; javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler; //对xml文档进行sax解析 public class Demo1 { /** * @param args * @throws SAXException * @throws ParserConfigurationException * @throws IOException */ public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException { //1.创建sax解析工厂 SAXParserFactory factory = SAXParserFactory.newInstance(); //2.得到sax解析器 SAXParser parser = factory.newSAXParser(); //3.得到xml文档读取器 XMLReader reader = parser.getXMLReader(); //4.设置好内容处理器 reader.setContentHandler(new ListHandler()); //5.读取xml文档 reader.parse("src/book.xml"); } } class ListHandler extends DefaultHandler{ @Override public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException { //null System.out.println("<" + name + ">"); for(int i=0;attributes!=null && i<attributes.getLength();i++){ String attName = attributes.getQName(i); String attValue = attributes.getValue(i); System.out.println(attName + "=" + attValue); } } @Override public void characters(char[] ch, int start, int length) throws SAXException { String content = new String(ch,start,length); System.out.println(content); } @Override public void endElement(String uri, String localName, String name) throws SAXException { System.out.println("</" + name + ">"); } }  

 

3..

import java.io.IOException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler; //获取xml文档中指定标签的值:<书名>Java就业培训教程</书名> public class Demo2 { /** * @param args * @throws SAXException * @throws ParserConfigurationException * @throws IOException */ public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException { //1.创建sax解析工厂 SAXParserFactory factory = SAXParserFactory.newInstance(); //2.得到sax解析器 SAXParser parser = factory.newSAXParser(); //3.得到xml文档读取器 XMLReader reader = parser.getXMLReader(); //4.设置好内容处理器 reader.setContentHandler(new TagValueHandler()); //5.读取xml文档 reader.parse("src/book.xml"); } } //获取xml文档中指定标签的值:<书名>Java就业培训教程</书名> class TagValueHandler extends DefaultHandler{ private String currentTag = null; private int needNum = 1; private int currentNum = 0; @Override public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException { currentTag = name; if("书名".equals(currentTag)){ currentNum++; } } @Override public void characters(char[] ch, int start, int length) throws SAXException { if("书名".equals(currentTag) && currentNum==needNum){ System.out.println(new String(ch,start,length)); } } }  

 

4...

import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler; //获取xml文档中指定标签的值:<书名>Java就业培训教程</书名> public class Demo3 { /** * @param args * @throws SAXException * @throws ParserConfigurationException * @throws IOException */ public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException { //1.创建sax解析工厂 SAXParserFactory factory = SAXParserFactory.newInstance(); //2.得到sax解析器 SAXParser parser = factory.newSAXParser(); //3.得到xml文档读取器 XMLReader reader = parser.getXMLReader(); //4.设置好内容处理器 BeanListHandler handler = new BeanListHandler(); reader.setContentHandler(handler); //5.读取xml文档 reader.parse("src/book.xml"); handler.getAll(); } } class BeanListHandler extends DefaultHandler{ private String currentTag = null; private Book book = null; private List list = new ArrayList(); @Override public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException { currentTag = name; if("书".equals(currentTag)){ book = new Book(); } } @Override public void characters(char[] ch, int start, int length) throws SAXException { if("书名".equals(currentTag)){ String name = new String(ch,start,length); book.setName(name); } if("作者".equals(currentTag)){ String author = new String(ch,start,length); book.setAuthor(author); } if("售价".equals(currentTag)){ String price = new String(ch,start,length); book.setPrice(price); } } @Override public void endElement(String uri, String localName, String name) throws SAXException { if("书".equals(name)){ list.add(book); book = null; } currentTag = null; } public List getAll(){ return list; } }  

 

你可能感兴趣的:(XML的jaxp版DOM解析 和SAX解析)