xml解析是日常项目中用到比较多的技能,无论是配置参数或者数据都可以保存在xml文件中,同时也可以将xml作为传输数据的一种格式。本文将介绍两种基本解析方式:xml字符串解析和xml文件解析。
xml字符串解析
package com.discover.parse; import java.util.Iterator; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; import org.dom4j.Element; /** * @author 民团司令 * */ public class XmlStringParser { public static void main(String[] args){ String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +"<root><student><name>jim</name><age>12</age></student>" +"<student><name>jim</name><age>12</age></student></root>"; try { Document document = DocumentHelper.parseText(xml); Element root = document.getRootElement(); Iterator stuIterator = root.elementIterator("student"); while (stuIterator.hasNext()) { Element student = (Element)stuIterator.next(); String name = student.elementTextTrim("name"); String age = student.elementTextTrim("age"); System.out.println("name:"+name+",age:"+age); } } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }xml文件解析
package com.discover.parse; import java.io.File; import java.util.Iterator; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; /** * @author 民团司令 * */ public class XmlFileParser { /** * @param args */ public static void main(String[] args) { String xmlFilePath = XmlFileParser.class.getResource("").getPath()+"stuInfo.xml"; File xmlFile = new File(xmlFilePath); if(xmlFile.exists()) { SAXReader reader = new SAXReader(); try { Document document = reader.read(xmlFile); Element root = document.getRootElement(); Iterator stuIterator = root.elementIterator("student"); while (stuIterator.hasNext()) { Element student = (Element)stuIterator.next(); String name = student.elementTextTrim("name"); String age = student.elementTextTrim("age"); System.out.println("name:"+name+",age:"+age); } } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
两种解析方式都是采用的dom4j实现,该jar可以在如下官网下载 原文链接:https://www.f2er.com/xml/296534.html