XML文件操作(二)

  • SAX(Simple APIs for XML)解析操作

与DOM操作不同的是,SAX采用的是一种顺序的模式进行访问,且采用的是部分读取,是一种快速读取XML数据的方式,只能读取不能修改,使用SAX解析器进行操作时会触发一系列的事件

主要事件:startDocument文档开始、endDocument文档结束、startElement元素开始、endElement元素结束、characters元素内容

读取操作

  • 建立解析工厂
  • 构造解析器
  • 解析XML

public class MySax extends DefaultHandler {
	@Override
	public void startDocument() throws SAXException {
		System.out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
	}
	
	@Override
	public void endDocument() throws SAXException {
		System.out.println("\n文档读取结束");
	}
	
	@Override
		public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
			System.out.print("<");
			System.out.print(qName);
			if(attributes!=null) {
				for (int i = 0; i < attributes.getLength(); i++) {
					System.out.print(" "+attributes.getQName(i)+"=\""+attributes.getValue(i)+"\"");
				}
			}
			System.out.print(">");
		}
	@Override
		public void endElement(String uri, String localName, String qName) throws SAXException {
		System.out.print("</");
		System.out.print(qName);
		System.out.print(">");
		}
	@Override
	public void characters(char[] ch, int start, int length) throws SAXException {
		System.out.print(new String(ch, start, length));
	}
	
}
@Test
	public void testRead() throws ParserConfigurationException, SAXException, IOException {
		//建立解析工厂
		SAXParserFactory factory=SAXParserFactory.newInstance();
		//构造解析器
		SAXParser parser=factory.newSAXParser();
		//解析XML
		parser.parse(this.getClass().getClassLoader().getResource("xml.xml").getPath(), new MySax());
	}

猜你喜欢

转载自blog.csdn.net/qq_37575994/article/details/100076352
今日推荐