遍历嵌套的xml文件android

时间:2014-07-10 12:34:02

标签: android xml

我试图在Android中遍历嵌套的XML字符串,如下所示:

  <?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标记的下一个结果。有人可以帮助我的代码并告诉我哪里出错了吗?

2 个答案:

答案 0 :(得分: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对象或其他内容中。

答案 1 :(得分: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();
                }

然后获取每个单独的问题(及其所有信息 - 问题,答案,评级)以及该问题的相应关键字并添加到Question对象,然后循环返回。我没有把关键字XML解析放在问题循环中。希望这可以帮助那些正在努力解决类似问题的人。