java讀取XML的方法

來源:互聯網
上載者:User

標籤:vax   cep   jdom   blog   tco   讀取   遍曆   strong   children   

1.DOM 實現方法

xml檔案

<?xml version="1.0" encoding="utf-8"?><Accounts>   <Account type="type1">         <code>100001</code>         <pass>123</pass>         <name>張三</name>         <money>1000000.00</money>   </Account>   <Account type="type2">       <code>100002</code>       <pass>123</pass>       <name>李四</name>       <money>1000.00</money>    </Account></Accounts>

java檔案

package dom;import java.io.*;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.Node;import org.w3c.dom.NodeList;public class Dom {    public static void main(String arge[]) {        Element element = null;        // 可以使用絕對路勁        File f = new File("dom/book.xml");        // documentBuilder為抽象不能直接執行個體化(將XML檔案轉換為DOM檔案)        DocumentBuilder db = null;        DocumentBuilderFactory dbf = null;        try {            // 返回documentBuilderFactory返回工廠對象            dbf = DocumentBuilderFactory.newInstance();            // 返回db對象用documentBuilderFatory對象獲得返回documentBuildr對象            db = dbf.newDocumentBuilder();            // 得到一個DOM並返回給document對象            Document dt = db.parse(f);            // 得到一個elment根項目            element = dt.getDocumentElement();            // 輸出根項目的name            System.out.println("根項目:" + element.getNodeName());//Accounts            // 獲得根項目下的子節點            NodeList childNodes = element.getChildNodes();            // 遍曆根節點下的所有子節點            for (int i = 0; i < childNodes.getLength(); i++) {//5 #text Account #text Account #text  會把斷行符號算成子節點,實際只有兩個子節點                // 獲得每個對應位置i的結點                Node node1 = childNodes.item(i);                System.out.println("分別是="+node1.getNodeName());                if ("Account".equals(node1.getNodeName())) {                    // 如果節點的名稱為"Account",則輸出Account元素屬性type                    //NamedNodeMap   nnm = node1.getAttributes()的傳回值是NamedNodeMap對象                     //通過節點名稱返回結點對象Node node = getNamedItem("type")                    //getNodeValue()返回的是xml節點的值                    System.out.println("\r\n找到一篇帳號. 所屬地區: "                            + node1.getAttributes().getNamedItem("type")                                    .getNodeValue() + ". ");                    // 獲得<Accounts>下的節點                    NodeList nodeDetail = node1.getChildNodes();                    // 遍曆<Accounts>下的節點                    for (int j = 0; j < nodeDetail.getLength(); j++) {//9 #text  code  #text  pass #text  name  #text  money #text                         // 獲得<Accounts>元素每一個節點                        Node detail = nodeDetail.item(j);                        if ("code".equals(detail.getNodeName())) // 輸出code                            System.out                                    .println("卡號: " + detail.getTextContent());                        else if ("pass".equals(detail.getNodeName())) // 輸出pass                            System.out                                    .println("密碼: " + detail.getTextContent());                        else if ("name".equals(detail.getNodeName())) // 輸出name                            System.out                                    .println("姓名: " + detail.getTextContent());                        else if ("money".equals(detail.getNodeName())) // 輸出money                            System.out                                    .println("餘額: " + detail.getTextContent());                    }                }            }        }        catch (Exception e) {            e.printStackTrace();        }    }}
2.DOM4J 實現方法

XML檔案

<?xml version="1.0" encoding="UTF-8"?>  <RESULT>     <VALUE >       <NO>A1234</NO>       <ADDR>河南省鄭州市</ADDR>     </VALUE>     <VALUE>       <NO>B1234</NO>       <ADDR>河南省鄭州市二七區</ADDR>     </VALUE> </RESULT>

java檔案

package dom4J;import java.io.*;   import java.util.*;   import org.dom4j.*;   import org.dom4j.io.*; public class Test {    public static void main(String arge[]) {                try {            File f = new File("dom4J/a.xml");            SAXReader reader = new SAXReader();            //得到Document對象            Document doc = reader.read(f);            //獲得根節點            Element root = doc.getRootElement();            Element foo;            //elementIterator從根節點遍曆子節點            Iterator i = root.elementIterator("VALUE");            while(i.hasNext()){            //for (Iterator i = root.elementIterator("VALUE"); i.hasNext();) {                foo = (Element) i.next();                //得到節點的內容                System.out.print("車牌號碼:" + foo.elementText("NO"));                System.out.println("車主地址:" + foo.elementText("ADDR"));            }        } catch (Exception e) {            e.printStackTrace();        }    }}
3. J DOM實現方法

XML和上面相同,java代碼如下

package jdom;import java.io.File;import java.util.List;import org.jdom.Document;import org.jdom.Element;import org.jdom.input.SAXBuilder;public class Test {    public static void main(String arge[]) {            try {            SAXBuilder builder = new SAXBuilder();            Document doc = builder.build(new File("jdom/a.xml"));            Element foo = doc.getRootElement();            List allChildren = foo.getChildren();            for (int i = 0; i < allChildren.size(); i++) {                System.out.print("車牌號碼:"                        + ((Element) allChildren.get(i)).getChild("NO")                                .getText());                System.out.println("車主地址:"                        + ((Element) allChildren.get(i)).getChild("ADDR")                                .getText());            }        } catch (Exception e) {            e.printStackTrace();        }    }}

注意:2,3方法需要引入相對應的jar包使用

java讀取XML的方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.