JDOM解析XML

package com.taobao.front.util;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.Attribute;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * JDOM解析xml 需要pom导入包
 * Created by Administrator on 2017/8/5.
 */
public class XmlTest {

    public static void main(String[] args) {
        String path = "G:\\taobao\\taobao-service\\src\\main\\resources\\mapping\\GoodsMapper.xml";

        //创建一个SAX对象
        SAXBuilder saxBuilder = new SAXBuilder();

        try {
            saxBuilder.build(path);
            InputStream in  = new FileInputStream(path);

            Document document = saxBuilder.build(in);

            //获取根结点
            Element rootrelement = document.getRootElement();

            System.out.println(rootrelement);

            //获取根结点下的子结点
            List children = rootrelement.getChildren();

            for(Element e : children){

                int index= children.indexOf(e); //个数

                //知道结点下属性的名称直接获得属性名称的值,例如获得id属性的值
                String idvalue = e.getAttributeValue("id");
//                System.out.println("id 属性" +   ":" + idvalue);

                //获得节点下所有的属性
                List attribute = e.getAttributes();

                for(Attribute a : attribute){

                    String name = a.getName(); //属性名

                    String value = a.getValue();//属性值
                }
            }

            //遍历明确标签下的子标签
            Element resElement = rootrelement.getChild("resultMap");
            List  resChElement = resElement.getChildren();
            //遍历resultMap标签下的所有子标签
            for(Element e: resChElement){
                //获得每个子标签的名字
                String resChElementname = e.getName();
                System.out.println(resChElementname +" 标签下的属性");
                //获得子标签所哟的属性
                List attributes = e.getAttributes();
                //遍历子标签里的所有属性
                for(Attribute a: attributes){
                    String aname = a.getName();
                    String avalue  = a.getValue();
                    System.out.println(aname + " : " + avalue);
                }
                System.out.println(resChElementname +" 标签下的属性结束==");
            }

        } catch (JDOMException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

你可能感兴趣的:(JDOM解析XML)