2014-01-31 3 views
0

Мне нужно получить маршруты проезда из тега html_instructions из XML-файла, который возвращается в Google Directions. Возвращенный XML-файл имеет иерархию тегов как route -> leg -> step. Один тег маршрута имеет множество тегов для ног, а в одном теге ноги есть много шагов. Каждый тег шага имеет один тег. Мне нужно получить содержимое всего тега html_instructions из файла с помощью синтаксического анализа XML.Получение инструкций по вождению из тега <html_instructions> из файла XML в android

я не знаю, как анализировать через файл и получить нужный выход в андроиде

пожалуйста, помогите ..

моего кода, чтобы получить файл XML:

private void fetchData() { 
    StringBuilder urlString = new StringBuilder(); 
    urlString 
      .append("http://maps.google.com/maps/api/directions/xml?origin="); 
    urlString.append(lat1); 
    urlString.append(","); 
    urlString.append(lon1); 
    urlString.append("&destination=");// to 
    urlString.append(lat2); 
    urlString.append(","); 
    urlString.append(lon2); 
    urlString.append("&sensor=true&mode=driving"); 
    Log.d("url", "::" + urlString.toString()); 
    HttpURLConnection urlConnection = null; 
    URL url = null; 
    try { 
     url = new URL(urlString.toString()); 
     urlConnection = (HttpURLConnection) url.openConnection(); 
     urlConnection.setRequestMethod("GET"); 
     urlConnection.setDoOutput(true); 
     urlConnection.setDoInput(true); 
     urlConnection.connect(); 
     DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
     DocumentBuilder db = dbf.newDocumentBuilder(); 
     doc = (Document) db.parse(urlConnection.getInputStream());// Util.XMLfromString(response); 

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

я необходимо проанализировать объект документа «doc». Пример файла, возвращаемый Google:

<DirectionsResponse> 
<status>OK</status> 
<route> 
    <summary>I-40 W</summary> 
    <leg> 
    <step> 
    <travel_mode>DRIVING</travel_mode> 
    <start_location> 
    <lat>41.8507300</lat> 
    <lng>-87.6512600</lng> 
    </start_location> 
    <end_location> 
    <lat>41.8525800</lat> 
    <lng>-87.6514100</lng> 
    </end_location> 
    <polyline> 
    <points>[email protected]</points> 
    </polyline> 
    <duration> 
    <value>19</value> 
    <text>1 min</text> 
    </duration> 
    <html_instructions>Head <b>north</b> on <b>S Morgan St</b> toward <b>W Cermak Rd</b></html_instructions> 
    <distance> 
    <value>207</value> 
    <text>0.1 mi</text> 
    </distance> 
    </step> 
    ... 
    ... additional steps of this leg 
    ... 
    ... additional legs of this route 
    <duration> 
    <value>74384</value> 
    <text>20 hours 40 mins</text> 
    </duration> 
    <distance> 
    <value>2137146</value> 
    <text>1,328 mi</text> 
    </distance> 
    <start_location> 
    <lat>35.4675602</lat> 
    <lng>-97.5164276</lng> 
    </start_location> 
    <end_location> 
    <lat>34.0522342</lat> 
    <lng>-118.2436849</lng> 
    </end_location> 
    <start_address>Oklahoma City, OK, USA</start_address> 
    <end_address>Los Angeles, CA, USA</end_address> 
    <copyrights>Map data ©2010 Google, Sanborn</copyrights> 
    <overview_polyline> 
    <points>[email protected][email protected]`vnApw{A`[email protected]~w\|[email protected]{[email protected]@b}@[email protected][email protected]@jc|Bx}C`[email protected]|@[email protected]}Axf][email protected][email protected]{A~d{A|[email protected]`cFp~xBc`[email protected]@[email protected][email protected]@[email protected]|{CbtY~jGqeMb{iF|n\~mbDzeVh_Wr|Efc\x`Ij{kE}mAb~uF{cNd}xBjp][email protected]|[email protected]_Kv~eGyqTj_|@`uV`k|[email protected]}[email protected][email protected]`CnvHx`[email protected]@j|[email protected]|[email protected]`[email protected][email protected]}[email protected]`@|}[email protected]@jakEitAn{fB_a]lexClshBtmqAdmY_hLxiZd~XtaBndgC</points> 
    </overview_polyline> 
    <optimized_waypoint_index>0</optimized_waypoint_index> 
    <optimized_waypoint_index>1</optimized_waypoint_index> 
    <bounds> 
    <southwest> 
    <lat>34.0523600</lat> 
    <lng>-118.2435600</lng> 
    </southwest> 
    <northeast> 
    <lat>41.8781100</lat> 
    <lng>-87.6297900</lng> 
    </northeast> 
    </bounds> 
</route> 
</DirectionsResponse> 
+0

Что ваш требуется выход? –

+0

Мне нужен контент внутри тега html_instructions, появляющийся на каждом шаге в списке массивов – poo0111

ответ

3
public ArrayList<String> getInstructions (Document doc) { 
     NodeList nl1, nl2; 
     ArrayList<String> listDirections = new ArrayList<String>(); 
     nl1 = doc.getElementsByTagName("step"); 
     if (nl1.getLength() > 0) { 
      for (int i = 0; i < nl1.getLength(); i++) { 
       Node node1 = nl1.item(i); 
       nl2 = node1.getChildNodes(); 
       Node directionNode = nl2.item(getNodeIndex(nl2, "html_instructions")); 
       String instruction = directionNode.getTextContent(); 
       listDirections.add(instruction.replaceAll("\\<.*?>","")); 
      } 
     } 
     return listDirections; 
    } 
+0

  все еще извлечен – adadion

1

Вы можете использовать 'Html.fromHtml (HTML_TEXT)'

public ArrayList<String> getInstructions (Document doc) { 
    NodeList nl1, nl2; 
    ArrayList<String> listDirections = new ArrayList<String>(); 
    nl1 = doc.getElementsByTagName("step"); 
    if (nl1.getLength() > 0) { 
     for (int i = 0; i < nl1.getLength(); i++) { 
      Node node1 = nl1.item(i); 
      nl2 = node1.getChildNodes(); 
      Node directionNode = nl2.item(getNodeIndex(nl2, "html_instructions")); 
      String instruction = directionNode.getTextContent(); 

      listDirections.add(Html.fromHtml(instruction)); 
     } 
    } 
    return listDirections; 
+0

только что пробовал и работал с незначительными изменениями, это 'String.valueOf (Html.fromHtml (инструкция));' – adadion

 Смежные вопросы

  • Нет связанных вопросов^_^