java讀取xml文件的三種方法

xml既簡單又標準,值得擁有和學習,好多地方都用的到。
假設有這麼一個book.xml:

<?xml version="1.0" encoding="ISO-8859-1"?>
<!-- Copyright w3school.com.cn -->
<!-- W3School.com.cn bookstore example -->
-<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" cover="paperback">
<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>

一、w3c.DOM的方式讀取

1、代碼:

/**
     * java讀取xml文件四中方式之一
     * w3c.DOM方式實現
     * Red_ant
     * 20181105
     */ 
    public static Document useDomReadXml(String soucePath){
        File file = new File(soucePath);
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(file);
            return doc;
        } catch (Exception e) {
            System.err.println("讀取該xml文件失敗");
            e.printStackTrace();
        }
        return null;
    }

2、測試用例:

    /**
     * java以w3c.DOM方式讀取xml文件        
     */
    String soucePath = "E:\\AllFilesISHere\\testfile\\books.xml";
    org.w3c.dom.Document doc = AllServiceIsHere.useDomReadXml(soucePath);
    //讀取xml內部節點集合
    org.w3c.dom.NodeList nlst = doc.getElementsByTagName("book");
    //遍歷集合內容
    for (int i = 0; i < ((org.w3c.dom.NodeList) nlst).getLength(); i++) {
        String title = doc.getElementsByTagName("title").item(i).getFirstChild().getNodeValue();
        String creater = doc.getElementsByTagName("author").item(i).getFirstChild().getNodeValue();         
        String year = doc.getElementsByTagName("year").item(i).getFirstChild().getNodeValue();
        String price = doc.getElementsByTagName("price").item(i).getFirstChild().getNodeValue();
        System.err.println("標題"+ title);
        System.err.println("作者"+creater);
        System.err.println("年份"+ year);
        System.err.println("價格"+ price);
    }

3、演示結果:

java讀取xml文件的三種方法

二、Java以DOM4J的方式讀取xml文件

1、代碼:

/**
     * java讀取xml的四種方法之二
     * DOM4J方式實現
     */
    public static Element useDom4JReadXml(String soucePath){
        try {
            File file = new File(soucePath);
            SAXReader read = new SAXReader();
            org.dom4j.Document doc = read.read(file);
            Element root = doc.getRootElement();
            return root;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

2、測試:

/**
         * java以DOM4J的方式讀取xml
         */
    org.dom4j.Element ele = AllServiceIsHere.useDom4JReadXml(soucePath);
        org.dom4j.Element foo ;
        for (Iterator i = ele.elementIterator("book"); i.hasNext();) {
            foo = (org.dom4j.Element) i.next();
            String title = foo.elementText("title");
            String creater = foo.elementText("author");
            String year = foo.elementText("year");
            String price = foo.elementText("price");
            System.err.println("標題"+ title);
            System.err.println("作者"+creater);
            System.err.println("年份"+ year);
            System.err.println("價格"+ price);
        }

3、演示:

java讀取xml文件的三種方法

三、java以JDOM的方式實現讀取xml文件

1、代碼:

/**java讀取xml的四種方法之三
     * 以JDOM的方式實現讀取xml文件
     */
    public static org.jdom.Element useJDOMReadXml(String soucePath){
        try {
            SAXBuilder builder = new SAXBuilder();
            org.jdom.Document doc = builder.build(new File(soucePath));
            org.jdom.Element foo = doc.getRootElement();
            return foo;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

2、測試:

/**
     * java以JDOM的方式讀取xml
     */
org.jdom.Element foo = AllServiceIsHere.useJDOMReadXml(soucePath);
        @SuppressWarnings("unchecked")
        List<Element> chilLst = foo.getChildren();
        for (int i = 0; i < chilLst.size(); i++) {
            String title = ((org.jdom.Element) chilLst.get(i)).getChild("title").getText();
            String creater = ((org.jdom.Element) chilLst.get(i)).getChild("author").getText();
            String year = ((org.jdom.Element) chilLst.get(i)).getChild("year").getText();
            String price = ((org.jdom.Element) chilLst.get(i)).getChild("price").getText();
            System.err.println("標題"+ title);
            System.err.println("作者"+creater);
            System.err.println("年份"+ year);
            System.err.println("價格"+ price);
            System.err.println("**************--------------********");
        }

3、演示:

java讀取xml文件的三種方法

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章