2014-04-29 2 views
0

일부 XML을 문자열로 구문 분석하려고 시도 중이므로 outofbounds 예외가 발생합니다. 나는 웹 사이트, 즉 CTA Bus Tracker API로부터 텍스트를 얻으려고 노력하는 것뿐만 아니라 안드로이드에 상당히 익숙하다. XML의 한 블록은 다음과 같다 : 이것은 내 방법구문 분석 XML 오류입니다. 예외는 arrayindexoutofbounds 예외입니다.

<route> 
     <rt>1</rt> 
     <rtnm>Bronzeville/Union Station</rtnm> 
    </route> 

입니다 :

class loadRoutes extends AsyncTask<String, String, String[]> { 
    @Override 
    protected String[] doInBackground(String... strings) { 
     try { 
      URL routesURL = new URL(strings[0]); 
      BufferedReader in = new BufferedReader(new InputStreamReader(routesURL.openStream())); 
      String [] result = new String[2]; 
      String line; 
      while((line = in.readLine()) != null) { 
       if(line.contains("<rt>")) { 
        int firstPos = line.indexOf("<rt>"); 
        String tempNum = line.substring(firstPos); 
        tempNum = tempNum.replace("<rt>", ""); 
        int lastPos = tempNum.indexOf("</rt>"); 
        result[0] = tempNum.substring(0, lastPos); 
        in.readLine(); 
        firstPos = line.indexOf("<rtnm>"); 
        String tempName = line.substring(firstPos); 
        tempName = tempName.replace("<rtnm>", ""); 
        lastPos = tempName.indexOf("</rtnm>"); 
        result[1] = tempName.substring(0, lastPos); 
       } 
      } 
      in.close(); 
      return result; 
     } 
     catch (MalformedURLException e) { 
      e.printStackTrace(); 
     } 
     catch (IOException e) { 
      e.printStackTrace(); 
     } 
     return null; 
    } 

첫 번째 readline()rt와 라인에 도달하고, if 문에 다음, 그 라인을 잡고, readline() 다음 줄을 가져와야하는데,이 줄은 rtnm이어야합니다. 나는 계속 indexoutofbounds이라는 줄을 firstPos = line.indexOf("rtnm")에 보냈다.

+2

Sax 파서 또는 DOM을 사용하여 xml을 구문 분석 할 수 있습니다. – yugidroid

답변

0

while 루프는 이미 다음 행에서 읽었으므로 if 문에서 in.readLine();이 필요하지 않습니다. 다음과 같이 실행 해보십시오.

while((line = in.readLine()) != null) { 
      if(line.contains("<rt>")) { 
       int firstPos = line.indexOf("<rt>"); 
       String tempNum = line.substring(firstPos); 
       tempNum = tempNum.replace("<rt>", ""); 
       int lastPos = tempNum.indexOf("</rt>"); 
       result[0] = tempNum.substring(0, lastPos); 
      } else if (line.contains("<rtnm>") { 
       firstPos = line.indexOf("<rtnm>"); 
       String tempName = line.substring(firstPos); 
       tempName = tempName.replace("<rtnm>", ""); 
       lastPos = tempName.indexOf("</rtnm>"); 
       result[1] = tempName.substring(0, lastPos); 
      } 
     } 

또한 다른 클래스에 자신의 XML 구문 분석기를 작성하는 것이 더 쉽습니다. 이 XML parser android documentation에는 수행하려는 작업의 예가 나와 있습니다.

+0

팁 주셔서 감사합니다. XML 구문 분석기 설명서를 살펴 보겠습니다. – user3192092