最近在看Spring,感觉 xml+反射 可以完成很多事情, 其中 xml 可以利用jdom/dom4j 等解析工具进行解析
下面给出一个jdom 解析xml的例子
个人感觉jdom解析xml与javaScript的便准dom读取的函数有异曲同工之妙。如 js的Element.getAttribute("xxx")...
jdom的一下载地址 http://download.csdn.net/detail/manymore13/5049145
项目结构:
解析xml 的Java代码
import java.util.*; import org.jdom.*; import org.jdom.input.SAXBuilder; public class Sample { public static void main(String[] args) throws Exception{ SAXBuilder sb=new SAXBuilder(); Document doc=sb.build(Sample.class.getClassLoader().getResourceAsStream("beans.xml")); //构造文档对象 Element root=doc.getRootElement(); List<?> list=root.getChildren("bean"); for(int i=0;i<list.size();i++){ Element element=(Element)list.get(i); String id=element.getAttributeValue("id"); String clazz=element.getAttributeValue("class"); System.out.println("dom一层节点id: "+id); System.out.println("dom一层节点class: "+clazz); //看看是否有property if(element.getChildren("property") != null){ List<?> propertyList = element.getChildren("property"); for(int j=0; j<propertyList.size(); j++){ Element element2 = (Element)propertyList.get(j); String name = element2.getAttributeValue("name"); System.out.println("dom二层节点name: "+name); } } } SAXBuilder sx=new SAXBuilder(); Document doc1=sx.build(Sample.class.getClassLoader().getResourceAsStream("test.xml")); //构造文档对象 Element root1=doc1.getRootElement(); //获取根元素HD List<?> list1=root1.getChildren("disk"); for(int i=0;i<list.size();i++){ Element element=(Element)list1.get(i); String name=element.getAttributeValue("name"); String capacity=element.getChildText("capacity");//取disk子元素capacity的内容 String directories=element.getChildText("directories"); String files=element.getChildText("files"); String text = element.getText(); System.out.println("dom节点内的内容为(调用trim后):"+text.trim()); System.out.println("磁盘信息:"); System.out.println("分区盘符:"+name); System.out.println("分区容量:"+capacity); System.out.println("目录数:"+directories); System.out.println("文件数:"+files); System.out.println("-----------------------------------"); } } }
beans.xml
<beans> <bean id="u" class="com.bjsxt.dao.impl.UserDAOImpl" /> <bean id="userService" class="com.bjsxt.service.UserService" > <property name="userDAO" bean="u"/> </bean> </beans>
test.xml
<?xml version="1.0" encoding="UTF-8"?> <HD> <disk name="C"> xxxxxxxxx <capacity>8G</capacity> <directories>200</directories> <files>1580</files> </disk> <disk name="D"> <capacity>10G</capacity> <directories>500</directories> <files>3000</files> </disk> </HD>