Java解析XML的几种方法
DOM解析
①构建Document对象:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = bdf.newDocumentBuilder();
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(xml文件);
Document doc = bd.parse(is);
②遍历DOM对象
Document: XML文档对象,由解析器获取
NodeList: 节点数组
Node: 节点(包括element、#text)
Element: 元素,可用于获取属性参数
SAX(Simple API for XML)解析
【DefaultHandler类】
SAX事件处理程序的默认基类,实现了DTDHandler、ErrorHandler、ContextHandler和EntityResolver接口,通常
做法是,继承该基类,重写需要的方法,如startDocument()
【创建SAX解析器】
SAXParserFactory saxf = SAXParserFactory.newInstance();
SAXParser sax = saxf.newSAXParser();
注:关于遍历
①深度优先遍历(Depthi-First Traserval)
②广度优先遍历(Width-First Traserval)JDOM(Java-based Document Object Model)
DOM4J(Document Object Model for Java)
StAX(Streaming API for XML)