需要用jar包 dom4j-1.6.1.jar
字符串xml如下:
aa 22 1 0
10.1.1.2 9999 10.1.1.5 717 2 33
10.1.1.2 9999 10.1.1.9 878
解析代码:
import java.io.ByteArrayInputStream;import java.io.UnsupportedEncodingException;import java.util.Iterator;import org.dom4j.DocumentException;import org.dom4j.io.SAXReader;public class XMLParser { public static void main(String[] args) { String xml = ""; long start = System.currentTimeMillis(); SAXReader reader = new SAXReader(); try { org.dom4j.Document doc = reader.read(new ByteArrayInputStream(xml .getBytes("UTF-8"))); org.dom4j.Element root = doc.getRootElement(); org.dom4j.Element element; org.dom4j.Element element2; org.dom4j.Element element3; for (Iterator i = root.elementIterator("flw"); i.hasNext();) { element = (org.dom4j.Element) i.next(); System.out .println("name:[" + element.elementText("name") + "]"); System.out.println("age:[" + element.elementText("age") + "]"); for (Iterator j = element.elementIterator("instance_info"); j .hasNext();) { element2 = (org.dom4j.Element) j.next(); System.out.println("\tnum:[" + element2.elementText("num") + "]"); System.out.println("\tcode:[" + element2.elementText("code") + "]"); for (Iterator k = element2.elementIterator("instance"); k .hasNext();) { element3 = (org.dom4j.Element) k.next(); System.out.println("\t\tip:[" + element3.elementText("ip") + "]"); System.out.println("\t\tmask:[" + element3.elementText("mask") + "]"); } } } } catch (DocumentException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } long end = System.currentTimeMillis(); System.out.println("耗时:" + (end - start) + "ms"); }} aa 22 1 0
10.1.1.2 9999 10.1.1.5 717 2 33
10.1.1.2 9999 10.1.1.9 878