优点:
高效、简单、易用的Xml解析器。
学习时间,分分钟。
支持中文标签名与属性名,支持下划线,减号等分隔符。
解析速度超过,查找速度超快,支持格式化。
缺点:不支持Xml Schema,DTD校验。
Maven引用坐标:
<dependency> <groupId>org.tinygroup</groupId> <artifactId>org.tinygroup.xmlparser</artifactId> <version>0.1.0-SNAPSHOT</version> </dependency>
解析下面xml
<?xml version="1.0"?> <students> <student> <name>John</name> <grade>B</grade> <age>12</age> </student> <student> <name>Mary</name> <grade>A</grade> <age>11</age> </student> <student> <name>Simon</name> <grade>A</grade> <age>18</age> </student> </students>
示例代码:
public class TestXmlParser { public static void main(String[] args) throws Throwable { File file = new File("E:/test/students.xml "); XmlStringParser parser = new XmlStringParser(); XmlDocument document = parser.parse(IOUtils.readFromInputStream( new FileInputStream(file), "utf-8")); printStudents(document.getRoot()); } private static void printStudents(XmlNode studentsNode) { for(XmlNode studentNode:studentsNode.getSubNodes("student")){ printStuent(studentNode); } } private static void printStuent(XmlNode studentNode) { printSubTagByName(studentNode,"name"); printSubTagByName(studentNode,"grade"); printSubTagByName(studentNode,"age"); } private static void printSubTagByName(XmlNode studentNode,String tagName) { System.out.println( studentNode.getSubNode(tagName).getContent()); } }
格式化示例:
XmlDocument doc; doc = new XmlStringParser() .parse("aaa"); XmlFormater f = new XmlFormater(); System.out.println(f.format(doc));
运行结果:
aaa
性能测试:
构建下面的节点规模:
HtmlNode node = null; public NameFilterTest() { node = new HtmlNode("root"); for (int i = 0; i < 60; i++) { HtmlNode a = node.addNode(new HtmlNode("a" + i)); for (int j = 0; j < 60; j++) { HtmlNode b = a.addNode(new HtmlNode("b" + j)); for (int k = 0; k < 60; k++) { b.addNode(new HtmlNode("c" + k)); } } } }
也就是节点数60+6060+6060*60个节点数时,进行下面的查找:
long t21 = System.currentTimeMillis(); FastNameFilter fast = new FastNameFilter(node); long t22 = System.currentTimeMillis(); System.out.println("fast初始化用时" + (t22 - t21)); long t1 = System.currentTimeMillis(); String nodeName = null; for (int x = 0; x < 10000; x++) { nodeName = fast.findNode("b6").toString(); } // System.out.println(nodeName); long t2 = System.currentTimeMillis(); System.out.println("FastNameFilter用时" + (t2 - t1));
fast初始化用时130 FastNameFilter用时450
也就是说在219661个节点中,查找指定节点10000次,只用时450ms。
更多详细信息可以前往软件开发者博客:http://my.oschina.net/tinyframework/