标签:rate system ring encoding nts lan target inf dom
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(); } } } }
依据读者的要求附上第2种方式的stuInfo.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>
两种解析方式都是採用的dom4j实现,该jar能够在例如以下官网下载
标签:rate system ring encoding nts lan target inf dom
原文地址:http://www.cnblogs.com/ljbguanli/p/7019465.html