
Demo4j
demo4j是一个第三方的提供的一种专用于解析xml的工具类,功能十分强大;4—for;j—java。
步骤
1、获取核心类
2、获取document(整个xml文档)
3、获取beans
4、获取所有的资源bean—bean属性
package cn.ant.Demo;import java.util.List;import org.dom4j.Document;import org.dom4j.DocumentException;import org.dom4j.Element;import org.dom4j.io.SAXReader;import org.junit.Test;public class DemoTest {// @Testpublic static void fun() throws DocumentException{//1、获取核心类 获取读取xml文件的流SAXReader saxReader=new SAXReader();//2、获取document(整个xml文档,即dom树)Document document=saxReader.read("beanss.xml");//3、获取beansElement rootElement=document.getRootElement();//4、获取所有的子元素beanList<Element> allBeanElement =rootElement.elements();//遍历集合for(Element e:allBeanElement){//获取当前节点的属性和值String id=e.attributeValue("id");String className=e.attributeValue("className");//显示System.out.println("bean的属性:"+id+","+className);//获取该节点下的节点List<Element> prop=e.elements();for(Element p:prop){//获取当前节点的属性和值String name=p.attributeValue("name");String value=p.attributeValue("value");//显示System.out.println("property的属性:"+name+","+value);}//换行System.out.println();}}public static void main(String[] args) throws DocumentException {fun();}}
<?xml version="1.0" encoding="utf-8"?><beans><bean id="userId01" className="cn.ant.User"><property name="uid" value="u001"></property><property name="username" value="jack"></property><property name="password" value="123456"></property></bean><bean id="bookId002" className="cn.ant.Books"><property name="bid" value="u001"></property><property name="title" value="java从入门到放弃"></property><property name="price" value="88"></property></bean></beans>

