• XML DOM解析(Java)的一个简单实例


      关于DOM解析的基础内容见上一篇文章:http://www.cnblogs.com/mengdd/archive/2013/06/01/3112795.html

      

      JAXP(Java API for XML Parsing) :用于XML解析的Java API。

      本文通过一个实际的代码例子来说明如何用Java提供的DOM相关的类和接口解析XML:

      首先,是XML文档:books.xml

    <?xml version="1.0" encoding="ISO-8859-1"?>
    
    <bookstore>
        <book category="children">
              <title lang="en">Harry Potter</title> 
              <author>J K. Rowling</author> 
              <year>2005</year> 
              <price>29.99</price> 
        </book>
    
        <book category="cooking">
              <title lang="en">Everyday Italian</title> 
              <author>Giada De Laurentiis</author> 
              <year>2005</year> 
              <price>30.00</price> 
        </book>
    
        <book category="web">
              <title lang="en">Learning XML</title> 
              <author>Erik T. Ray</author> 
              <year>2003</year> 
              <price>39.95</price> 
        </book>
    
        <book category="web">
              <title lang="en">XQuery Kick Start</title> 
              <author>James McGovern</author> 
              <author>Per Bothner</author> 
              <author>Kurt Cagle</author> 
              <author>James Linn</author> 
             <author>Vaidyanathan Nagarajan</author> 
              <year>2003</year> 
              <price>49.99</price> 
        </book>
    
    </bookstore>

      把这个文档放在项目的根路径下,与src目录平行,就可以使用相对路径来引用了。

      新建Java类,解析如下:

    package com.example.xml.dom;
    
    import java.io.File;
    
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.NodeList;
    
    public class DomTest1
    {
        public static void main(String[] args) throws Exception
        {
            // step 1:获得DOM解析器工厂
            // 工厂的作用是创建具体的解析器
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    
            // step 2:获得具体的dom解析器
            DocumentBuilder db = dbf.newDocumentBuilder();
    
            // step 3:解析一个xml文档,获得Document对象(根节点)
            // 此文档放在项目目录下即可
            Document document = db.parse(new File("books.xml"));
    
            // 根据标签名访问节点
            NodeList list = document.getElementsByTagName("book");
            System.out.println("list length: " + list.getLength());
    
            // 遍历每一个节点
            for (int i = 0; i < list.getLength(); ++i)
            {
                System.out.println("----------------------");
                // 获得元素,将节点强制转换为元素
                Element element = (Element) list.item(i);
                // 此时element就是一个具体的元素
    
                // 获取子元素:子元素title只有一个节点,之后通过getNodeValue方法获取节点的值
                String content0 = element.getElementsByTagName("title").item(0)
                        .getNodeValue();
    
                System.out.println(content0);// 此处打印出为null
                // 因为节点getNodeValue的值永远为null
    
                // 解决方法:加上getFirstChild()
                String content = element.getElementsByTagName("title").item(0)
                        .getFirstChild().getNodeValue();
                System.out.println("title: " + content);// 此处打印出书名
    
                // 后面类似处理即可:
                content = element.getElementsByTagName("author").item(0)
                        .getFirstChild().getNodeValue();
                System.out.println("author: " + content);
                content = element.getElementsByTagName("year").item(0)
                        .getFirstChild().getNodeValue();
                System.out.println("year: " + content);
                content = element.getElementsByTagName("price").item(0)
                        .getFirstChild().getNodeValue();
                System.out.println("price: " + content);
            }
        }
    
    }

      具体过程参见注释。

      首先,我们需要建立一个解析器工厂,以利用这个工厂来获得一个具体的解析器对象。 

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

     

      我们在这里使用DocumentBuilderFactory的目的是为了创建与具体解析器无关的程序,当DocumentBuilderFactory类的静态方法newInstance()被调用时,它根据一个系统变量来决定具体使用哪一个解析器。

      又因为所有的解析器都服从于JAXP所定义的接口,所以无论具体使用哪一个解析器,代码都是一样的。

      所以当在不同的解析器之间进行切换时,值需要更改系统变量的值,而不用更改任何代码。这就是工厂所带来的好处。

    DocumentBuilder db = dbf.newDocumentBuilder();

      当获得一个工厂对象之后,使用它的静态方法newDocumentBuilder(),可以获得一个DocumentBuilder对象

      这个对象代表了具体的DOM解析器

      解析器的具体实现对于程序来说并不重要。  

      然后,我们就可以利用这个解析器对文档进行解析了。

      Sun公司提供了默认的工厂和默认的解析器,上面的例子中就使用了默认的解析器。

    参考资料

      圣思园张龙老师XML视频教程。

      w3school XML DOM 教程:

      http://www.w3school.com.cn/xmldom/index.asp

      Java API文档:

      http://docs.oracle.com/javase/7/docs/api/index.html

  • 相关阅读:
    洛谷 P1635 跳跃
    python write() argument must be str, not bytes
    python write() argument must be str, not bytes
    Python hashlib Unicode-objects must be encoded before hashing
    Python hashlib Unicode-objects must be encoded before hashing
    洛谷P1629 邮递员送信
    TypeError: Error when calling the metaclass bases Cannot create a consistent method resolution
    TypeError: Error when calling the metaclass bases Cannot create a consistent method resolution
    [USACO07FEB]银牛派对Silver Cow Party
    [USACO09OPEN]捉迷藏Hide and Seek
  • 原文地址:https://www.cnblogs.com/mengdd/p/3113291.html
Copyright © 2020-2023  润新知