문제

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 getting 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);
    }
} 
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top