XML解析:SAX及Xpath分别解析xml

主要包含以下内容:

 

1.与DOM相比较,SAX的调用属于轻量级。DOM需要把所生成的DOM树加载至内存;

2.SAX的优势:文档读入过程即为SAX的解析过程;

  SAX的劣势:顺序读取,开发过程需处理应用程序

示例1:

import java.io.File; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class SAXTest extends DefaultHandler { private String tagValue; long starttime; long endtime; public static void main(String[] args) { String filename = "c:/test.xml"; SAXParserFactory spf = SAXParserFactory.newInstance(); try { SAXParser saxParser = spf.newSAXParser(); saxParser.parse(new File(filename), new SAXTest()); } catch (Exception e) { e.printStackTrace(); } } // 开始解析XML文件 public void startDocument() throws SAXException { // 可以在此初始化变量等操作 System.out.println("~~~~解析文档开始~~~"); // starttime=System.currentTimeMillis(); starttime = System.nanoTime(); } // 结束解析XML文件 public void endDocument() throws SAXException { // endtime=System.currentTimeMillis(); endtime = System.nanoTime(); System.out.println("~~~~解析文档结束~~~"); // System.out.println("共用"+(endtime-starttime)+"毫秒"); System.out.println("共用" + (endtime - starttime) + "纳秒"); } /** * 在解释到一个开始元素时会调用此方法.但是当元素有重复时可以自己写算法来区分 * */ public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { System.out.println("startElement处标签名:" + qName); if (attributes != null && attributes.getLength() != 0) { System.out.print("--" + "该标签有属性值:"); for (int i = 0; i < attributes.getLength(); i++) { System.out.print(attributes.getQName(i) + "="); System.out.print(attributes.getValue(i) + " "); } System.out.println(); } } /** * 在遇到结束标签时调用此方法 */ public void endElement(String uri, String localName, String qName) throws SAXException { System.out.print("endElement处的值是:"); System.out.println(tagValue); } /** * 所有的XML文件中的字符会放到ch[]中 */ public void characters(char ch[], int start, int length) throws SAXException { tagValue = new String(ch, start, length).trim(); } } 

 

3.Xpath结合Java进行xml路径解析

import java.io.IOException; import org.w3c.dom.*; import org.xml.sax.SAXException; import javax.xml.parsers.*; import javax.xml.xpath.*; public class XPATHTest { public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException { DocumentBuilderFactory domFactory = DocumentBuilderFactory .newInstance(); domFactory.setNamespaceAware(true); // never forget this! DocumentBuilder builder = domFactory.newDocumentBuilder(); Document doc = builder.parse("c:/solr.xml"); XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); Node nd = (Node)xpath.evaluate("solr/cores/@adminPath", doc, XPathConstants.NODE); String txt = nd.getNodeValue(); System.out.println(txt); //多核循环读取,属性读取 XPath mulXpath = factory.newXPath(); Object o = mulXpath.evaluate("solr/cores/core", doc, XPathConstants.NODESET); NodeList nodes = (NodeList) o; for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); Node aNode =(Node) node.getAttributes().getNamedItem("name"); System.out.println(aNode.getNodeValue()); // String opt = DOMUtil.getAttr(node, "name", null); // System.out.println(opt); System.out.println(node.getNodeName()); Node eNode = node.getFirstChild(); System.out.println(eNode.getNodeValue()); System.out.println(node.getNodeType()); } } } 

 

xml文档如下

<?xml version="1.0" encoding="UTF-8" ?> <!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <!-- All (relative) paths are relative to the installation path persistent: Save changes made via the API to this file sharedLib: path to a lib directory that will be shared across all cores --> <solr persistent="false"> <!-- adminPath: RequestHandler path to manage cores. If 'null' (or absent), cores will not be manageable via request handler --> <cores adminPath="/admin/cores"> <core name="core0" instanceDir="core0" >afklajsdlfja</core> <core name="core1" instanceDir="core1" >vbab</core> </cores> </solr>  

 

 

4.结合DOM和SAX特点的JDOM,需依赖二者的包

 

 <?xml version="1.0" encoding="utf-8"?> <books> <book email="zhoujunhui"> <name>rjzjh</name> <price>60.0</price> </book> </books> 

JDOM解析:

public class JDomParse { public JDomParse(){ String xmlpath="library.xml"; SAXBuilder builder=new SAXBuilder(false); try { Document doc=builder.build(xmlpath); Element books=doc.getRootElement(); List booklist=books.getChildren("book"); for (Iterator iter = booklist.iterator(); iter.hasNext();) { Element book = (Element) iter.next(); String email=book.getAttributeValue("email"); System.out.println(email); String name=book.getChildTextTrim("name"); System.out.println(name); book.getChild("name").setText("alterrjzjh"); } XMLOutputter outputter=new XMLOutputter(); outputter.output(doc,new FileOutputStream(xmlpath)); } catch (JDOMException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { new JDomParse(); } } 

 

你可能感兴趣的:(XML解析:SAX及Xpath分别解析xml)