dom4j 解析xml 文档

来源:互联网 发布:飞鸽传书经典mac 编辑:程序博客网 时间:2024/06/05 10:58
<?xml version='1.0' encoding='UTF-8'?>
<Root>
    <mess>
        <property name="sSize" value="52"></property>
        <property name="cSize" value="23"></property>
        <property name="pSize" value="15"></property>
        <property name="aSize" value="25"></property>
    </mess>
    <table>
        <property name="c" value="52c"></property>
        <property name="a" value="23a"></property>
        
    </table>

</Root>





package com.test.bao;

import java.io.File;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.QName;
import org.dom4j.io.SAXReader;

public class OrgDomTest {

    private static String path="src/com/test/bao/test.xml";
    public String praseXml(String name) throws DocumentException{
           SAXReader reader = new SAXReader();  

//另外一种加载文件路径位置

        InputStream is =null;
           is= this.getClass().getClassLoader().getResourceAsStream(
                   "main/config/tablename.xml");


           Document  document = reader.read(new File(path));

           Element root = document.getRootElement();
           List<Element>  emList= root.elements();
           for(Element e:emList){
               QName q=e.getQName();
               if(q.getName().equals("mess")){
                   List<Element> childs=e.elements();
                  for(Element child:childs){
                      if(child.attributeValue("name").equals(name)){
                          return child.attributeValue("value");
                      }
                  }
               }else  if(q.getName().equals("table")){
                   List<Element> childs=e.elements();
                  for(Element child:childs){
                      if(child.attributeValue("name").equals(name)){
                          return child.attributeValue("value");
                      }
                  }
               }
           }
        return null;
    }
    
    public static void main(String[] args) {
        OrgDomTest org=new OrgDomTest();
        try {
            String name= org.praseXml("sSize");
            String name1=org.praseXml("pSize");
            String name2=org.praseXml("PSize");
            System.out.println("输出护具2   "+name2);
            System.out.println("输出护具1   "+name1);
            System.out.println("输出护具   "+name);
            
            String name3=org.praseXml("c");
            System.out.println("输出table数据 "+ name3);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

}


0 0
原创粉丝点击