簡體   English   中英

如何在Android應用程序中解析XML文件

[英]How to parse an XML file in an Android app

我正在嘗試解析XML文件,如下所示

<Subject>
    <chapter>
       <Question>abc</Question>
       <answer>avksn</answer>
    </chapter>
    <chapter>
        <Question>def</Question>
       <answer>avksn</answer>
    </chapter>
    <chapter>
         <Question>ccsv</Question>
        <answer>avksn</answer>
    </chapter>
</Subject>

在這我能夠計算章的數量。 章的數量等於問答的數量。 我還在我的布局中放置了一個名為ok的按鈕。

現在我想顯示第一個問題,點擊確定后我想顯示第二個問題,直到結束。 當我到達最后一個問題時,我想轉移到一個新的活動。

如何執行此操作,請幫助我

將XML讀入文檔(v = xml字符串)

public Document XMLfromString(){

    Document doc = null;

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    try {

        DocumentBuilder db = dbf.newDocumentBuilder();

        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(v));
        doc = db.parse(is); 

    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        System.out.println("Wrong XML file structure: " + e.getMessage());
        return null;
    } catch (IOException e) {
        e.printStackTrace();
    }

    return doc;

}

然后得到這樣的元素:

/** Returns element value
  * @param elem element (it is XML tag)
  * @return Element value otherwise empty String
  */
 public final static String getElementValue( Node elem ) {
     Node kid;
     if( elem != null){
         if (elem.hasChildNodes()){
             for( kid = elem.getFirstChild(); kid != null; kid = kid.getNextSibling() ){
                 if( kid.getNodeType() == Node.TEXT_NODE  ){
                     return kid.getNodeValue();
                 }
             }
         }
     }
     return "";
 }

如何使用:

Document doc = x.XMLfromString();
NodeList nodes = doc.getElementsByTagName("result");

    for (int i = 0; i < nodes.getLength(); i++) {                           
        HashMap<String, String> map = new HashMap<String, String>();    

        Element e = (Element)nodes.item(i);
        map.put("id", x.getValue(e, "orgid"));
        map.put("bedrijf", x.getValue(e, "naam"));
        map.put("plaats", x.getValue(e, "plaats"));
        mylist.add(map);            
    }

將xml讀入InputStream,然后:

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.parse([the InpuTstream]);

然后你可以使用doc:

  if(doc.getElementsByTagName("GeometryCollection").getLength()>0){
    org.w3c.dom.Node parent_node = doc.getElementsByTagName("GeometryCollection").item(0);
    NodeList nl = parent_node.getChildNodes();
    for(int i = 0;i<nl.getLength();i++){
     ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM