» 首頁 » 討論區 » Android程式設計 »取得XML節點資料

取得XML節點資料

發表人: Seachaos
積分: 2432
發表時間: 2009-11-14 15:13:55
以下是Android分析XML資料的方法
有點類似於JavaScript的用法

以下程式碼是利用getElementById取得XML的Value
[quote]
==========================
try {
                    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                    DocumentBuilder db = dbf.newDocumentBuilder();
                    InputSource is = new InputSource();
                    URL url = new URL("http://localhost/text.xml");                    
                    is.setByteStream(url.openStream());
                    Document doc = db.parse(is);
                    try{
                        Element ele = doc.getElementById("NodeID");
                        Node nod = ele.getFirstChild();
                        text=nod.getNodeValue();
                    }catch(DOMException e){
                        text=e.toString();
                    }
                } catch (ParserConfigurationException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    text="e1";
                } catch (SAXException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    text=e.toString();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    text="e3";
                }

====================
[/quote]
發表人: Seachaos
積分: 2432
發表時間: 2009-11-19 09:22:41
以下方法可以由String直接產生InputSource
也就是說可以直接把String轉化成XML讀取
[quote]
StringReader str = new StringReader("<xml></xml>");
InputSource is = new InputSource();
is.setCharacterStream(str);
[/quote]