JDOM解析XML

首先要有jdom的jar包资源。此处引用的是 jdom-2.0.6.jar
上代码:

import java.util.List;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;



public class JDomXML {
    private static int num = 1;
    public static void main(String []args){
        try{
            SAXBuilder builder = new SAXBuilder();
            Document doc = builder.build("books.xml");
            Element ele = doc.getRootElement();
            getElementChild(ele); //第二种方法:遍历节点的方法封装在另一个方法中
            /*
             * 第一种方法:利用for循环遍历的方法,遍历出子节点
             * List childs = ele.getChildren();
            for(int i =0;i<childs.size();i++){
                Element child = (Element)childs.get(i);
                System.out.println("---------------------------");
                System.out.println(child.getName());//获取节点名
                System.out.println("---------------------------");
                if(child.getChildren().size()>0){ //判断是否有子节点
                    List list = child.getChildren();
                    for(int j=0;j<list.size();j++){
                        Element book = (Element)list.get(j);
                        System.out.println(book.getName());
                    }
                }
            }*/

        }catch(Exception e){
            e.printStackTrace();
        }
    }

    public static void  getElementChild(Element ele){

        List childs = ele.getChildren();
        System.out.println("num="+num++); //作为标识,
        if(childs == null || childs.size()<=0){
            return ;
        }
        for(int i =0;i<childs.size();i++){
            Element child = (Element)childs.get(i);
            System.out.println("---------------------------");
            System.out.println(child.getName());//获取节点名
            System.out.println(child.getText());
            //getElementChild(child); //第二种方法:这样递归的层数变多了
            if(child.getChildren().size()>0){ // 第一种方法:判断是否有子节点
                getElementChild(child);
            }
        }
    }


}

上XML文件:

<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
    <book  >
        <name>父与子</name>
        <author>劳恩</author>
        <year>2016</year>
        <price>23</price>
        <paper >
            <jiage>
                <meike>22</meike>
                <result>33</result>
            </jiage>
            <count>24</count>
        </paper>
    </book>
    <book >
        <name>父与子</name>
        <author>劳恩</author>
        <year>2016</year>
        <price>23</price>
    </book>

</bookstore>

以下代码取自 jdom-2.0.6.jar 中

关于SAXBuilder 类中的 builder.build(“books.xml”)
SAXBuilder 的构造函数启到了重要作用
先上SAXBuilder 的构造函数,再上build的方法

构造函数:

public SAXBuilder()
  {
    this(null, null, null);
  }

public SAXBuilder(XMLReaderJDOMFactory xmlreaderfactory, SAXHandlerFactory handlerfactory, JDOMFactory jdomfactory)
  {
  //XMLReaders.NONVALIDATING 枚举类对象
    this.readerfac = (xmlreaderfactory == null ? XMLReaders.NONVALIDATING : xmlreaderfactory);

    this.handlerfac = (handlerfactory == null ? DEFAULTSAXHANDLERFAC : handlerfactory);

    this.jdomfac = (jdomfactory == null ? DEFAULTJDOMFAC : jdomfactory);
  }

build(String systenId)方法:

 public Document build(String systemId)
    throws JDOMException, IOException
  {
    if (systemId == null) {
      throw new NullPointerException("Unable to build a URI from a null systemID.");
    }
    try
    {
      Document localDocument = getEngine().build(systemId);
      return localDocument;
    }
    catch (IOException ioe)
    {
      int len = systemId.length();
      int i = 0;
      while ((i < len) && (Verifier.isXMLWhitespace(systemId.charAt(i)))) {
        i++;
      }
      if ((i < len) && ('<' == systemId.charAt(i)))
      {
        MalformedURLException mx = new MalformedURLException("SAXBuilder.build(String) expects the String to be a systemID, but in this instance it appears to be actual XML data.");

        mx.initCause(ioe);
        throw mx;
      }

      throw ioe;
    } finally {
      if (!this.reuseParser)
        this.engine = null; 
    }throw localObject;
  }

  /*build(String systemId)中调用的getEngine()的源码,engine这个定义一开始为 null,在初始化SAXBuilder 也没有给他赋值,所以这个方法最后调用了buildEngine()这个方法。
  */
  private SAXEngine getEngine()
    throws JDOMException
  {
    if (this.engine != null) {
      return this.engine;
    }

    this.engine = buildEngine();
    return this.engine;
  }

  //所调用buildEngine()的方法的源码,其中this.readerfac方法是在构造函数中进行赋值的
  public SAXEngine buildEngine()
    throws JDOMException
  {
  /*
    源码中SAXHandler 的定义:public class SAXHandler extends DefaultHandler
  implements LexicalHandler, DeclHandler, DTDHandler{//省略};
  继承的DefaultHandler是提供xml解析的回调函数
    */
    SAXHandler contentHandler = this.handlerfac.createSAXHandler(this.jdomfac); 

    contentHandler.setExpandEntities(this.expand);
    contentHandler.setIgnoringElementContentWhitespace(this.ignoringWhite);
    contentHandler.setIgnoringBoundaryWhitespace(this.ignoringBoundaryWhite);
    /* 
       XMLReader 是进行解析XML的工具 ,通过 createParser 方法创建
    */
    XMLReader parser = createParser();

    configureParser(parser, contentHandler);
    /*this.readerfac是类中定义的方法,在构造函数中,给予这个对象一个枚举类 如下:public enum XMLReaders
  implements XMLReaderJDOMFactory
{//省略}
*/
    boolean valid = this.readerfac.isValidating();
    return new SAXBuilderEngine(parser, contentHandler, valid);
  }

//createParser 方法,该方法最后返回的 XMLReader是由 this.readerfac.createXMLReader() 该方法提供,this.readerfac为枚举的对象
protected XMLReader createParser()
    throws JDOMException
  {
    XMLReader parser = this.readerfac.createXMLReader();
    //this.saxXMLFilter 初始化定义为 null ,暂未检查到有调用给他赋值的方法
    if (this.saxXMLFilter != null) 
    {
      XMLFilter root = this.saxXMLFilter;
      while ((root.getParent() instanceof XMLFilter)) {
        root = (XMLFilter)root.getParent();
      }
      root.setParent(parser);

      parser = this.saxXMLFilter;
    }

    return parser;
  }

XMLReaders 枚举类涉及的相关方法

//XMLReaders中的this.readerfac.createXMLReader() 源码详情
 public XMLReader createXMLReader()
    throws JDOMException
  {
    try
    {
    /*FactorySupplier 为抽象接口类 ,getSupplier 调用了NONSingleton内部枚举类,调用NONSingleton构造函数,返回NONSingleton(有实现FactorySupplier 接口)对象给FactorySupplier 
      */
      FactorySupplier supplier = getSupplier(); 
      /*
      通过 supply()方法获取SAXParserFactory对象,然后创建XMLReader对象--这里获取对象跟SAX解析方式类似
      */
      return supplier.supply().newSAXParser().getXMLReader();
    } catch (SAXException e) {
      throw new JDOMException("Unable to create a new XMLReader instance", e);
    }
    catch (ParserConfigurationException e) {
      throw new JDOMException("Unable to create a new XMLReader instance", e);
    } catch (Exception e) {
    }
    throw new JDOMException("It was not possible to configure a suitable XMLReader to support " + this, e);
  }

看到这里,
Jdom与SAX小区别:
jdom只需要你调用,不需要创建新的类
SAX需要你自己去创建,

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值