开发者

Android - Pull Parser

I am having one xml file and I want to parse it to get Student-ids and student-names only.

<students>
    <student>
         <id type="integer">101</id>
         <name>James</name>
         <degree>
             <id type="integer">1978271</id>
             <name>SCJP</name>
         </degree>
    </student>
    <student>
         <id type="integer">102</id>
         <name>Joseph</name>
         <degree>
             <id type="integer">1978272</id>
             <name>MCST</name>
         </degree>
    </student>
</students>

Code:

while (eventType != XmlPullParser.END_DOCUMENT) {
    parser.next();
    eventType = parser.getEventType();
    switch (eventType){
    case XmlPullParser.START_TAG:   
         tag_name = parser.getName();
         if(tag_name.equalsIgnoreCase("ID")){
              stud_id = parser.nextText().toString();
              Log.i("Id = ", pid);
          } else if (tag_name.equalsIgnoreCase("name")){
              stud_name = parser.nextText().toString();
          } 
          break;
     }
} 

My Problem: When I am parsing the XML file using the above code,I am getti开发者_JAVA百科ng both the IDs(i.e. student-id, degree-id), so Using Pull-parser, which way I should parse the XML file to get list of only Student-id` ?


When you encounter a starting tag matching "student", set some boolean variable (called insideStudent for example) to true. Similarly, when you encounter a "degree" tag set another insideDegree variable to true. When you have a closing tag, set them to false (e.g. if you have </student> then you set insideStudent to false). Now when you encounter an ID tag, you just need to check if you're only inside student or inside both of degree and student. Something like:

if(tag_name.equalsIgnoreCase("ID")){
    // Get student ID
    if (insideStudent && !insideDegree) {
          stud_id = parser.nextText().toString();
          Log.i("Id = ", pid);
    }
} 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜