JAVA解析XML格式字串 【常用】__JAVA

來源:互聯網
上載者:User

文章來源:http://blog.sina.com.cn/s/blog_700dec940100spox.html

他使用的是jdom.jar解析xml檔案

import java.io.IOException;
import java.io.StringReader;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.Namespace;
import org.jdom.input.SAXBuilder;
import org.xml.sax.InputSource;

public class DuXMLDoc {
    public List xmlElements(String xmlDoc) {
        //建立一個新的字串
        StringReader read = new StringReader(xmlDoc);
        //建立新的輸入源SAX 解析器將使用 InputSource 對象來確定如何讀取 XML 輸入
        InputSource source = new InputSource(read);
        //建立一個新的SAXBuilder
        SAXBuilder sb = new SAXBuilder();
        try {
            //通過輸入源構造一個Document
            Document doc = sb.build(source);
            //取的根項目
            Element root = doc.getRootElement();
            System.out.println(root.getName());//輸出根項目的名稱(測試)
            //得到根項目所有子項目的集合
            List jiedian = root.getChildren();
            //獲得XML中的命名空間(XML中未定義可不寫)
            Namespace ns = root.getNamespace();
            Element et = null;
            for(int i=0;i<jiedian.size();i++){
                et = (Element) jiedian.get(i);//迴圈依次得到子項目
               
                System.out.println(et.getChild("users_id",ns).getText());
                System.out.println(et.getChild("users_address",ns).getText());
            }
           
            et = (Element) jiedian.get(0);
    

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.