2014-07-10 249 views
0

我試圖穿越在Android的一個嵌套的XML字符串,它看起來像這樣:遍歷嵌套的XML文件的Android

<?xml version="1.0" encoding="UTF-8" standalone="no"?> 
    <Results> 
    <Result> 
     <Questions> 
     <Question>Where can I get the local variable</Question> 
     <Answer>In the local method</Answer> 
     <AverageRating>3.0</AverageRating> 
     </Questions> 
     <Keywords> 
     <Keyword>Methods</Keyword> 
     <Keyword>Returns</Keyword> 
     <Keyword>Void</Keyword> 
     </Keywords> 
    </Result> 
    <Result> 
     <Questions> 
     <Question>How can I do a nested for loop</Question> 
     <Answer>Easy</Answer> 
     <AverageRating>2.5</AverageRating> 
     </Questions> 
     <Keywords> 
     <Keyword>Methods</Keyword> 
     <Keyword>Returns</Keyword> 
     <Keyword>Void</Keyword> 
     <Keyword>Methods</Keyword> 
     <Keyword>Returns</Keyword> 
     </Keywords> 
    </Result> 

與以下的Android代碼:

 try 
    { 
     //Creates the document 
     DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
     DocumentBuilder builder = factory.newDocumentBuilder(); 
     Document document = builder.parse(new InputSource(new StringReader(serverResult))); 

    //optional, but recommended 
    //read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work 
    document.getDocumentElement().normalize(); 

    //Look at root node's type (e.g. <query> or <login> or <add>) 
    String rootNode = document.getDocumentElement().getNodeName().toString(); 

    if (rootNode.equals("Results")) 
    { 
     String Question = ""; 
     String Answer = ""; 
     String AverageRating = ""; 
     float rating = 0; 
     String keyword = ""; 

     NodeList nList = document.getElementsByTagName("Result"); 
     for (int i = 0; i < nList.getLength(); i++) 
     { 
     Node nodes = nList.item(i); 
     if (nodes.getNodeType() == Node.ELEMENT_NODE) 
     { 
      Element element = (Element) nodes;        
      NodeList list = document.getElementsByTagName("Questions"); 

      for (int value = 0; value < list.getLength(); value++) 
      { 
       Node node = list.item(value); 

       if (node.getNodeType() == Node.ELEMENT_NODE) 
       { 
        Element eElement = (Element) node;        
        Question = getValue("Question", eElement); 
        Answer = getValue("Answer", eElement); 
        AverageRating = getValue("AverageRating", eElement); 
        rating = Float.parseFloat(AverageRating); 
       } 
      } 
     } 

     NodeList keywordNode = document.getElementsByTagName("Keywords"); 
     String keywords = ""; 
     for (int y = 0; y < keywordNode.getLength(); y++) 
     { 
      Node node = keywordNode.item(y); 

      if (node.getNodeType() == Node.ELEMENT_NODE) 
      { 
       Element element = (Element) node; 
       NodeList ModList = document.getElementsByTagName("Keyword"); 
       int count = ModList.getLength(); 
       for (int b = 0; b < count; b++) 
        { 

      keyword = element.getElementsByTagName("Keyword").item(b).getTextContent(); 
      keywords = keywords + keyword + "\n"; 
        } 
      } 
    items.add(new Question(Question, Answer, rating, keywords)); 
    }        
} 
} 
    } 
catch (Exception e) 
{ 
String s = e.getMessage(); 
publishProgress(s); 
} 

我試圖實現的是在我的XML的Result標籤中的每個各自的結果的每一個問題,我想這個問題(和它的細節)和相應的關鍵字,增加每到Question類,然後從Results標籤重複下一個結果。有人可以幫助我的代碼,並告訴我我要去哪裏錯了嗎?

回答

0

嘗試導入這些:通過在該網站下載他們

import org.xmlpull.v1.XmlPullParser; 
import org.xmlpull.v1.XmlPullParserException; 
import org.xmlpull.v1.XmlPullParserFactory; 

http://www.xmlpull.org/

然後,嘗試一個代碼結構是這樣的:

String XMLin; 
    XmlPullParserFactory factory; 
    String tag; 
    ArrayList<Question> questions = new ArrayList<Question>(); 
    try { 
     XMLin = readString(instream); 
    } catch (IOException e1) { 
     // TODO Auto-generated catch block 
     XMLin = "Something went wrong"; 
    } 
    try { 
     // Set up the Class that will be parsing the xml file 
     factory = XmlPullParserFactory.newInstance(); 
     factory.setNamespaceAware(true); 
     XmlPullParser xpp = factory.newPullParser(); 
     xpp.setInput(new StringReader (XMLin)); 

     // Get the first event type 
     int eventType = xpp.getEventType(); 
     while (eventType != XmlPullParser.END_DOCUMENT) { 
     // While we have not reached the end of the document, check for start tags 
      if (eventType == XmlPullParser.START_TAG) { 
       tag = xpp.getName(); 

       if (tag.equals("Questions") && eventType == XmlPullParser.START_TAG) { 
        Question question = new Question(); 
        do { 
         if (tag.equals("Question")) { 
          // Add question text to question 
          eventType = xpp.next(); 
           String text = xpp.getText(); // Text between tags 
         } else if (tag.equals("Answer")) { 
           eventType = xpp.next(); 
           String text = xpp.getText(); // Text between tags 
         } else if (tag.equals("AvergaeRating") { 
            eventType = xpp.next(); 
           String text = xpp.getText(); // Text between tags 
         } 
         eventType = xpp.next(); 
         if (eventType == XmlPullParser.TEXT) { 
          tag = xpp.getText(); 
         } else { 
          tag = xpp.getName(); 
         } 
        } while (!tag.equals("Questions")) 
        questions.add(question); 
       } 
       } 
      } 

這是東西變形例我曾經通過XML解析。從本質上講,檢查標籤名稱和事件(無論是開始標籤還是結束標籤等),然後根據這兩個值執行所需的操作,例如將文本添加到Question對象或什麼內容中。

0

我設法使用此代碼:

   try 
       { 
        //Creates the document 
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
        DocumentBuilder builder = factory.newDocumentBuilder(); 
        Document document = builder.parse(new InputSource(new StringReader(serverResult))); 

        //optional, but recommended 
        //read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work 
        document.getDocumentElement().normalize(); 

         //Look at root node's type (e.g. <query> or <login> or <add>) 
         String rootNode = document.getDocumentElement().getNodeName().toString(); 

         if (rootNode.equals("Results")) 
         { 
          //Any methods which need to be called that will be used to query the database 
          //Always sending the String XML through as a parameter 
          //Look at the child node 
          String Question = ""; 
          String Answer = ""; 
          String AverageRating = ""; 
          float rating = 0; 

          String keywords = ""; 
          NodeList nList = document.getElementsByTagName("Questions"); 

          System.out.println("----------------------------"); 

          for (int temp = 0; temp < nList.getLength(); temp++) 
          { 
           Node nNode = nList.item(temp); 
           System.out.println("\nCurrent Element :" + nNode.getNodeName()); 
           if (nNode.getNodeType() == Node.ELEMENT_NODE) 
           { 

            Element eElement = (Element) nNode; 

            Question = getValue("Question", eElement); 
            Answer = getValue("Answer", eElement); 
            AverageRating = getValue("AverageRating", eElement); 
            rating = Float.parseFloat(AverageRating); 

            NodeList List = document.getElementsByTagName("Keywords"); 


             for (int a = 0; a < List.getLength(); a++) 
              { 

              Node node = List.item(temp); 

                if (node.getNodeType() == Node.ELEMENT_NODE) 
                { 
                 Element element = (Element) node; 
                 String Keyword = element.getElementsByTagName("Keyword").item(0).getTextContent(); 
                 keywords = keywords + Keyword + "\n"; 
                } 

              } 
           } 
           items.add(new Question(Question, Answer, rating, keywords)); 
          } 

         } 
       } 
       catch (IOException e) { 
        e.printStackTrace(); 
       } catch (ParserConfigurationException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } catch (SAXException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 

然後得到的每一個單獨的問題(以及他們的所有信息 - 問題,答案,評分)和以及對這個問題的各個關鍵詞,並加入到一個問題對象,然後循環回來。我沒有把關鍵字XML解析放在循環問題中。希望這可以幫助那些正在解決類似問題的人。