【弁言】
现在在Java中用于剖析XML的手艺很多,主流的有DOM、SAX、JDOM、DOM4j,下文重要引见这4种剖析XML文档手艺的运用、优瑕玷及机能测试。
一、【基本知识——扫盲】
sax、dom是两种对xml文档举行剖析的要领(没有细致完成,只是接口),所以只需它们是没法剖析xml文档的;jaxp只是api,它进一步封装了sax、dom两种接口,而且供应了DomcumentBuilderFactory/DomcumentBuilder和SAXParserFactory/SAXParser(默许运用xerces诠释器)。
二、【DOM、SAX、JDOM、DOM4j简朴运用引见】
1、【DOM(Document Object Model) 】
由W3C供应的接口,它将全部XML文档读入内存,构建一个DOM树来对各个节点(Node)举行操纵。
示例代码:
<?xml version="1.0" encoding="UTF-8"?> <university name="pku"> <college name="c1"> <class name="class1"> <student name="stu1" sex='male' age="21" /> <student name="stu2" sex='female' age="20" /> <student name="stu3" sex='female' age="20" /> </class> <class name="class2"> <student name="stu4" sex='male' age="19" /> <student name="stu5" sex='female' age="20" /> <student name="stu6" sex='female' age="21" /> </class> </college> <college name="c2"> <class name="class3"> <student name="stu7" sex='male' age="20" /> </class> </college> <college name="c3"> </college> </university>
后文代码中有运用到text.xml(该文档放在src途径下,既编译后在classes途径下),都是指该xml文档。
package test.xml; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Text; import org.xml.sax.SAXException; /** * dom读写xml * @author whwang */ public class TestDom { public static void main(String[] args) { read(); //write(); } public static void read() { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { DocumentBuilder builder = dbf.newDocumentBuilder(); InputStream in = TestDom.class.getClassLoader().getResourceAsStream("test.xml"); Document doc = builder.parse(in); // root <university> Element root = doc.getDocumentElement(); if (root == null) return; System.err.println(root.getAttribute("name")); // all college node NodeList collegeNodes = root.getChildNodes(); if (collegeNodes == null) return; for(int i = 0; i < collegeNodes.getLength(); i++) { Node college = collegeNodes.item(i); if (college != null && college.getNodeType() == Node.ELEMENT_NODE) { System.err.println("\t" + college.getAttributes().getNamedItem("name").getNodeValue()); // all class node NodeList classNodes = college.getChildNodes(); if (classNodes == null) continue; for (int j = 0; j < classNodes.getLength(); j++) { Node clazz = classNodes.item(j); if (clazz != null && clazz.getNodeType() == Node.ELEMENT_NODE) { System.err.println("\t\t" + clazz.getAttributes().getNamedItem("name").getNodeValue()); // all student node NodeList studentNodes = clazz.getChildNodes(); if (studentNodes == null) continue; for (int k = 0; k < studentNodes.getLength(); k++) { Node student = studentNodes.item(k); if (student != null && student.getNodeType() == Node.ELEMENT_NODE) { System.err.print("\t\t\t" + student.getAttributes().getNamedItem("name").getNodeValue()); System.err.print(" " + student.getAttributes().getNamedItem("sex").getNodeValue()); System.err.println(" " + student.getAttributes().getNamedItem("age").getNodeValue()); } } } } } } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static void write() { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { DocumentBuilder builder = dbf.newDocumentBuilder(); InputStream in = TestDom.class.getClassLoader().getResourceAsStream("test.xml"); Document doc = builder.parse(in); // root <university> Element root = doc.getDocumentElement(); if (root == null) return; // 修正属性 root.setAttribute("name", "tsu"); NodeList collegeNodes = root.getChildNodes(); if (collegeNodes != null) { for (int i = 0; i <collegeNodes.getLength() - 1; i++) { // 删除节点 Node college = collegeNodes.item(i); if (college.getNodeType() == Node.ELEMENT_NODE) { String collegeName = college.getAttributes().getNamedItem("name").getNodeValue(); if ("c1".equals(collegeName) || "c2".equals(collegeName)) { root.removeChild(college); } else if ("c3".equals(collegeName)) { Element newChild = doc.createElement("class"); newChild.setAttribute("name", "c4"); college.appendChild(newChild); } } } } // 新增节点 Element addCollege = doc.createElement("college"); addCollege.setAttribute("name", "c5"); root.appendChild(addCollege); Text text = doc.createTextNode("text"); addCollege.appendChild(text); // 将修正后的文档保存到文件 TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer transFormer = transFactory.newTransformer(); DOMSource domSource = new DOMSource(doc); File file = new File("src/dom-modify.xml"); if (file.exists()) { file.delete(); } file.createNewFile(); FileOutputStream out = new FileOutputStream(file); StreamResult xmlResult = new StreamResult(out); transFormer.transform(domSource, xmlResult); System.out.println(file.getAbsolutePath()); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (TransformerConfigurationException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } } }
该代码只需稍做修正,即可变得越发简约,无需一直写if来推断是不是有子节点。
2、【SAX (Simple API for XML) 】
SAX不必将全部文档加载到内存,基于事宜驱动的API(Observer形式),用户只须要注册本身感兴趣的事宜即可。SAX供应EntityResolver, DTDHandler, ContentHandler, ErrorHandler接口,离别用于监听剖析实体事宜、DTD处置惩罚事宜、正文处置惩罚事宜和处置惩罚失足事宜,与AWT相似,SAX还供应了一个对这4个接口默许的类DefaultHandler(这里的默许完成,实在就是一个空要领),平常只需继续DefaultHandler,重写本身感兴趣的事宜即可。
示例代码:
package test.xml; import java.io.IOException; import java.io.InputStream; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.helpers.DefaultHandler; /** * * @author whwang */ public class TestSAX { public static void main(String[] args) { read(); write(); } public static void read() { try { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); InputStream in = TestSAX.class.getClassLoader().getResourceAsStream("test.xml"); parser.parse(in, new MyHandler()); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static void write() { System.err.println("纯SAX关于写操纵无计可施"); } } // 重写对本身感兴趣的事宜处置惩罚要领 class MyHandler extends DefaultHandler { @Override public InputSource resolveEntity(String publicId, String systemId) throws IOException, SAXException { return super.resolveEntity(publicId, systemId); } @Override public void notationDecl(String name, String publicId, String systemId) throws SAXException { super.notationDecl(name, publicId, systemId); } @Override public void unparsedEntityDecl(String name, String publicId, String systemId, String notationName) throws SAXException { super.unparsedEntityDecl(name, publicId, systemId, notationName); } @Override public void setDocumentLocator(Locator locator) { super.setDocumentLocator(locator); } @Override public void startDocument() throws SAXException { System.err.println("最先剖析文档"); } @Override public void endDocument() throws SAXException { System.err.println("剖析完毕"); } @Override public void startPrefixMapping(String prefix, String uri) throws SAXException { super.startPrefixMapping(prefix, uri); } @Override public void endPrefixMapping(String prefix) throws SAXException { super.endPrefixMapping(prefix); } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { System.err.print("Element: " + qName + ", attr: "); print(attributes); } @Override public void endElement(String uri, String localName, String qName) throws SAXException { super.endElement(uri, localName, qName); } @Override public void characters(char[] ch, int start, int length) throws SAXException { super.characters(ch, start, length); } @Override public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { super.ignorableWhitespace(ch, start, length); } @Override public void processingInstruction(String target, String data) throws SAXException { super.processingInstruction(target, data); } @Override public void skippedEntity(String name) throws SAXException { super.skippedEntity(name); } @Override public void warning(SAXParseException e) throws SAXException { super.warning(e); } @Override public void error(SAXParseException e) throws SAXException { super.error(e); } @Override public void fatalError(SAXParseException e) throws SAXException { super.fatalError(e); } private void print(Attributes attrs) { if (attrs == null) return; System.err.print("["); for (int i = 0; i < attrs.getLength(); i++) { System.err.print(attrs.getQName(i) + " = " + attrs.getValue(i)); if (i != attrs.getLength() - 1) { System.err.print(", "); } } System.err.println("]"); } }
3、【JDOM】
JDOM与DOM异常相似,它是处置惩罚XML的纯JAVA API,API大批运用了Collections类,且JDOM仅运用细致类而不运用接口。 JDOM 它本身不包含剖析器。它一般运用 SAX2 剖析器来剖析和考证输入 XML 文档(只管它还能够将之前组织的 DOM 示意作为输入)。它包含一些转换器以将 JDOM 示意输出成 SAX2 事宜流、DOM 模子或 XML 文本文档
示例代码:
package test.xml; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.List; import org.jdom.Attribute; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; import org.jdom.output.XMLOutputter; /** * JDom读写xml * @author whwang */ public class TestJDom { public static void main(String[] args) { //read(); write(); } public static void read() { try { boolean validate = false; SAXBuilder builder = new SAXBuilder(validate); InputStream in = TestJDom.class.getClassLoader().getResourceAsStream("test.xml"); Document doc = builder.build(in); // 猎取根节点 <university> Element root = doc.getRootElement(); readNode(root, ""); } catch (JDOMException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } @SuppressWarnings("unchecked") public static void readNode(Element root, String prefix) { if (root == null) return; // 猎取属性 List<Attribute> attrs = root.getAttributes(); if (attrs != null && attrs.size() > 0) { System.err.print(prefix); for (Attribute attr : attrs) { System.err.print(attr.getValue() + " "); } System.err.println(); } // 猎取他的子节点 List<Element> childNodes = root.getChildren(); prefix += "\t"; for (Element e : childNodes) { readNode(e, prefix); } } public static void write() { boolean validate = false; try { SAXBuilder builder = new SAXBuilder(validate); InputStream in = TestJDom.class.getClassLoader().getResourceAsStream("test.xml"); Document doc = builder.build(in); // 猎取根节点 <university> Element root = doc.getRootElement(); // 修正属性 root.setAttribute("name", "tsu"); // 删除 boolean isRemoved = root.removeChildren("college"); System.err.println(isRemoved); // 新增 Element newCollege = new Element("college"); newCollege.setAttribute("name", "new_college"); Element newClass = new Element("class"); newClass.setAttribute("name", "ccccc"); newCollege.addContent(newClass); root.addContent(newCollege); XMLOutputter out = new XMLOutputter(); File file = new File("src/jdom-modify.xml"); if (file.exists()) { file.delete(); } file.createNewFile(); FileOutputStream fos = new FileOutputStream(file); out.output(doc, fos); } catch (JDOMException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
4、【DOM4j】
dom4j是现在在xml剖析方面是最优异的(Hibernate、Sun的JAXM也都运用dom4j来剖析XML),它兼并了很多超越基本 XML 文档示意的功用,包含集成的 XPath 支撑、XML Schema 支撑以及用于大文档或流化文档的基于事宜的处置惩罚
示例代码:
package test.xml; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.util.List; import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.ProcessingInstruction; import org.dom4j.VisitorSupport; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; /** * Dom4j读写xml * @author whwang */ public class TestDom4j { public static void main(String[] args) { read1(); //read2(); //write(); } public static void read1() { try { SAXReader reader = new SAXReader(); InputStream in = TestDom4j.class.getClassLoader().getResourceAsStream("test.xml"); Document doc = reader.read(in); Element root = doc.getRootElement(); readNode(root, ""); } catch (DocumentException e) { e.printStackTrace(); } } @SuppressWarnings("unchecked") public static void readNode(Element root, String prefix) { if (root == null) return; // 猎取属性 List<Attribute> attrs = root.attributes(); if (attrs != null && attrs.size() > 0) { System.err.print(prefix); for (Attribute attr : attrs) { System.err.print(attr.getValue() + " "); } System.err.println(); } // 猎取他的子节点 List<Element> childNodes = root.elements(); prefix += "\t"; for (Element e : childNodes) { readNode(e, prefix); } } public static void read2() { try { SAXReader reader = new SAXReader(); InputStream in = TestDom4j.class.getClassLoader().getResourceAsStream("test.xml"); Document doc = reader.read(in); doc.accept(new MyVistor()); } catch (DocumentException e) { e.printStackTrace(); } } public static void write() { try { // 建立一个xml文档 Document doc = DocumentHelper.createDocument(); Element university = doc.addElement("university"); university.addAttribute("name", "tsu"); // 解释 university.addComment("这个是根节点"); Element college = university.addElement("college"); college.addAttribute("name", "cccccc"); college.setText("text"); File file = new File("src/dom4j-modify.xml"); if (file.exists()) { file.delete(); } file.createNewFile(); XMLWriter out = new XMLWriter(new FileWriter(file)); out.write(doc); out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } } } class MyVistor extends VisitorSupport { public void visit(Attribute node) { System.out.println("Attibute: " + node.getName() + "=" + node.getValue()); } public void visit(Element node) { if (node.isTextOnly()) { System.out.println("Element: " + node.getName() + "=" + node.getText()); } else { System.out.println(node.getName()); } } @Override public void visit(ProcessingInstruction node) { System.out.println("PI:" + node.getTarget() + " " + node.getText()); } }
三、【机能测试】
环境:AMD4400+ 2.0+GHz主频 JDK6.0
运转参数:-Xms400m -Xmx400m
xml文件大小:10.7M
效果:
DOM: >581297ms
SAX: 8829ms
JDOM: 581297ms
DOM4j: 5309ms
时候包含IO的,只是举行了简朴的测试,仅供参考!!!!
四、【对照】
1、【DOM】
DOM是基于树的构造,一般须要加载整文档和组织DOM树,然后才最先事情。
长处:
a、因为整棵树在内存中,因而能够对xml文档随机接见
b、能够对xml文档举行修正操纵
c、较sax,dom运用也更简朴。
瑕玷:
a、全部文档必需一次性剖析完
a、因为全部文档都须要载入内存,关于大文档本钱高
2、【SAX】
SAX相似流媒体,它基于事宜驱动的,因而无需将全部文档载入内存,运用者只须要监听本身感兴趣的事宜即可。
长处:
a、无需将全部xml文档载入内存,因而斲丧内存少
b、能够注册多个ContentHandler
瑕玷:
a、不能随机的接见xml中的节点
b、不能修正文档
3、【JDOM】
JDOM是纯Java的处置惩罚XML的API,其API中大批运用Collections类,
长处:
a、DOM体式格局的长处
b、具有SAX的Java划定规矩
瑕玷
a、DOM体式格局的瑕玷
4、【DOM4J】
这4中xml剖析体式格局中,最优异的一个,集易用和机能于一身。
五、【小插曲XPath】
XPath 是一门在 XML 文档中查找信息的言语, 可用来在 XML 文档中对元素和属性举行遍历。XPath 是 W3C XSLT 规范的重要元素,而且 XQuery 和 XPointer 同时被构建于 XPath 表达之上。因而,对 XPath 的明白是很多高等 XML 运用的基本。
XPath异常相似对数据库操纵的SQL言语,或者说JQuery,它能够轻易开发者抓起文档中须要的东西。(dom4j也支撑xpath)
示例代码:
package test.xml; import java.io.IOException; import java.io.InputStream; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class TestXPath { public static void main(String[] args) { read(); } public static void read() { try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = dbf.newDocumentBuilder(); InputStream in = TestXPath.class.getClassLoader().getResourceAsStream("test.xml"); Document doc = builder.parse(in); XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); // 拔取一切class元素的name属性 // XPath语法引见: http://w3school.com.cn/xpath/ XPathExpression expr = xpath.compile("//class/@name"); NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); for (int i = 0; i < nodes.getLength(); i++) { System.out.println("name = " + nodes.item(i).getNodeValue()); } } catch (XPathExpressionException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
六、【补充】
注重4种剖析要领对TextNode(文本节点)的处置惩罚:
1、在运用DOM时,挪用node.getChildNodes()猎取该节点的子节点,文本节点也会被看成一个Node来返回,如:
<?xml version="1.0" encoding="UTF-8"?> <university name="pku"> <college name="c1"> <class name="class1"> <student name="stu1" sex='male' age="21" /> <student name="stu2" sex='female' age="20" /> <student name="stu3" sex='female' age="20" /> </class> </college> </university>
package test.xml; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * dom读写xml * @author whwang */ public class TestDom2 { public static void main(String[] args) { read(); } public static void read() { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { DocumentBuilder builder = dbf.newDocumentBuilder(); InputStream in = TestDom2.class.getClassLoader().getResourceAsStream("test.xml"); Document doc = builder.parse(in); // root <university> Element root = doc.getDocumentElement(); if (root == null) return; // System.err.println(root.getAttribute("name")); // all college node NodeList collegeNodes = root.getChildNodes(); if (collegeNodes == null) return; System.err.println("university子节点数:" + collegeNodes.getLength()); System.err.println("子节点以下:"); for(int i = 0; i < collegeNodes.getLength(); i++) { Node college = collegeNodes.item(i); if (college == null) continue; if (college.getNodeType() == Node.ELEMENT_NODE) { System.err.println("\t元素节点:" + college.getNodeName()); } else if (college.getNodeType() == Node.TEXT_NODE) { System.err.println("\t文本节点:" + Arrays.toString(college.getTextContent().getBytes())); } } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
输出的效果是:
university子节点数:3 子节点以下: 文本节点:[10, 9] 元素节点:college 文本节点:[10]
个中\n的ASCII码为10,\t的ASCII码为9。效果让人大吃一惊,university的子节点数不是1,也不是2,而是3,这3个子节点都是谁呢?为了看得更清晰点,把xml文档改成:
<?xml version="1.0" encoding="UTF-8"?> <university name="pku">11 <college name="c1"> <class name="class1"> <student name="stu1" sex='male' age="21" /> <student name="stu2" sex='female' age="20" /> <student name="stu3" sex='female' age="20" /> </class> </college>22 </university>
照样上面的顺序,输出效果为:
university子节点数:3 子节点以下: 文本节点:[49, 49, 10, 9] 元素节点:college 文本节点:[50, 50, 10]
个中数字1的ASCII码为49,数字2的ASCII码为50。
2、运用SAX来剖析同DOM,当你重写它的public void characters(char[] ch, int start, int length)要领时,你就可以看到。
3、JDOM,挪用node.getChildren()只返回子节点,不包含TextNode节点(不论该节点是不是有Text信息)。假如要猎取该节点的Text信息,能够挪用node.getText()要领,该要领返回节点的Text信息,也包含\n\t等特别字符。
4、DOM4j同JDOM
以上就是java剖析xml的示例代码汇总的细致内容,更多请关注ki4网别的相干文章!