来自URL的XML解析在Android中不起作用

问题描述:

我想从url执行XML Parsing。以下是使用xml解析的代码,但它不起作用。任何人都可以帮助我相应地获得response来自URL的XML解析在Android中不起作用

public class MainActivity extends AppCompatActivity { 

    // Declare variables 
    TextView textview; 
    NodeList nodelist; 
    ProgressDialog pDialog; 

    // Insert image URL 
// String URL = "http://www.androidbegin.com/tutorial/XMLParseTutorial.xml"; 
    String URL = "my private url"; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     new DownloadXML().execute(URL); 

     textview = (TextView) findViewById(R.id.text); 
    } 


    // DownloadXML AsyncTask 
    private class DownloadXML extends AsyncTask<String, Void, Void> { 

     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      // Create a progressbar 
      pDialog = new ProgressDialog(MainActivity.this); 
      // Set progressbar title 
      pDialog.setTitle("Android Simple XML Parsing using DOM Tutorial"); 
      // Set progressbar message 
      pDialog.setMessage("Loading..."); 
      pDialog.setIndeterminate(false); 
      // Show progressbar 
      pDialog.show(); 
     } 

     @Override 
     protected Void doInBackground(String... Url) { 
      try { 
       URL url = new URL(Url[0]); 
       DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 

       DocumentBuilder db = dbf.newDocumentBuilder(); 
       // Download the XML file 
       Document doc = db.parse(new InputSource(url.openStream())); 
       doc.getDocumentElement().normalize(); 

       Log.e("testing "," ==>"); 


       // Locate the Tag Name 
//    nodelist = doc.getElementsByTagName("item"); 
       nodelist = doc.getElementsByTagName("ApiResponseOfTwiliosZ_PlQ1mzg"); 

      } catch (Exception e) { 
       Log.e("Error", e.getMessage()); 
       e.printStackTrace(); 
      } 
      return null; 

     } 

     @Override 
     protected void onPostExecute(Void args) { 

      for (int temp = 0; temp < nodelist.getLength(); temp++) { 
       Node nNode = nodelist.item(temp); 
       if (nNode.getNodeType() == Node.ELEMENT_NODE) { 
        Element eElement = (Element) nNode; 
        // Set the texts into TextViews from item nodes 
        // Get the title 


        Log.e("Message checking "," ===> "+getNode("ResponseStatus", eElement)); 



       } 
      } 
      // Close progressbar 
      pDialog.dismiss(); 
     } 
    } 

    // getNode function 
    private static String getNode(String sTag, Element eElement) { 
     NodeList nlList = eElement.getElementsByTagName(sTag).item(0) 
       .getChildNodes(); 
     Node nValue = (Node) nlList.item(0); 
     return nValue.getNodeValue(); 
    } 
} 

和错误如下所示。

java.lang.NullPointerException: Attempt to invoke interface method 'int org.w3c.dom.NodeList.getLength()' on a null object reference 

enter image description here

在这里,我想从这个回应得到token

下面是我api response

<ApiResponseOfTwiliosZ_PlQ1mzg xmlns:i="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns="http://schemas.datacontract.org/2004/07/Healthcare4Free.WebApi.Models"> 
<Data i:nil="true"/> 
<ResponseStatus> 
<Message>Success</Message> 
<StatusCode>200</StatusCode> 
<TwilioToken> 
<Token> 
eyJjdHkiOiJ0d2lsaW8tZnBhO3Y9MSIsInR5cCI6IkpXVCIsImFsZyI6IkhTMjU2In0.eyJpc3MiOiJTSzMxZDVjM2NiNDVmMjQ2ZjI5NDY4MTFlOGQxYWZlYjM4IiwiZXhwIjoxNTA4Njc4NzYzLCJqdGkiOiJTSzMxZDVjM2NiNDVmMjQ2ZjI5NDY4MTFlOGQxYWZlYjM4LTE1MDg2NzUxNjMiLCJzdWIiOiJBQzdlNDBhZjY1YTYwMGYyYmQ3Yjg2Zjk1OTFkZjM4ZTFiIiwiZ3JhbnRzIjp7ImlkZW50aXR5IjoiaWRlbnRpdHkiLCJ2aWRlbyI6eyJyb29tIjoicm9vbUlkIn19fQ.yHKcOOiUrVZKYsQ3110YzgprRpODd9fp1dQLQFNw7Gw 
</Token> 
</TwilioToken> 
</ResponseStatus> 
</ApiResponseOfTwiliosZ_PlQ1mzg> 
+0

你的节点列表是null.Error可以是在节点列表= doc.getElementsByTagName( “ApiResponseOfTwiliosZ_PlQ1mzg”); –

+0

@ M M感谢您的回复,但您可以帮助我使用示例代码,以便我可以轻松整合它。 –

+0

@M M感谢您的快速回复。其实我不能分享原始的网址,但它完全正常工作,在这个问题中附加到这个图像的反应。我需要示例代码来获得适当的响应。在此先感谢 –

要获得令牌代码更新为:

在doInBackground()

nodelist = doc.getElementsByTagName("TwilioToken"); 

在你onPostExecute()

Log.e("Message checking ", " ===> " + getNode("Token", eElement)); 

以下是完整的代码:

TextView textview; 

    NodeList nodelist; 
    ProgressDialog pDialog; 
    String URL = "http://json-gen.com/rest/service/get/uCSFzJgDKrjq7DKCNiQtm"; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     new DownloadXML().execute(URL); 

     textview = (TextView) findViewById(R.id.text); 
    } 


    // DownloadXML AsyncTask 
    private class DownloadXML extends AsyncTask<String, Void, Void> { 

     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      // Create a progressbar 
      pDialog = new ProgressDialog(MainActivity.this); 
      // Set progressbar title 
      pDialog.setTitle("Android Simple XML Parsing using DOM Tutorial"); 
      // Set progressbar message 
      pDialog.setMessage("Loading..."); 
      pDialog.setIndeterminate(false); 
      // Show progressbar 
      pDialog.show(); 
     } 

     @Override 
     protected Void doInBackground(String... Url) { 
      try { 
       URL url = new URL(Url[0]); 
       DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 

       DocumentBuilder db = dbf.newDocumentBuilder(); 
       // Download the XML file 
       Document doc = db.parse(new InputSource(url.openStream())); 
       doc.getDocumentElement().normalize(); 

       Log.e("testing ", " ==>"); 


       // Locate the Tag Name 
//    nodelist = doc.getElementsByTagName("item"); 
       nodelist = doc.getElementsByTagName("TwilioToken"); 

      } catch (Exception e) { 
       Log.e("Error", e.getMessage()); 
       e.printStackTrace(); 
      } 
      return null; 

     } 

     @Override 
     protected void onPostExecute(Void args) { 

      Node nNode = nodelist.item(0); 
      if (nNode.getNodeType() == Node.ELEMENT_NODE) { 
       Element eElement = (Element) nNode; 
       // Set the texts into TextViews from item nodes 
       // Get the title 


       Log.e("Message checking ", " ===> " + getNode("Token", eElement)); 
       textview.setText(getNode("Token", eElement)); 

      } 
      // Close progressbar 
      pDialog.dismiss(); 
     } 
    } 

    // getNode function 
    private static String getNode(String sTag, Element eElement) { 
     NodeList nlList = eElement.getElementsByTagName(sTag).item(0) 
       .getChildNodes(); 
     Node nValue = (Node) nlList.item(0); 
     return nValue.getNodeValue(); 
    } 
+0

@MMI尝试使用此解决方案,但得到像这样的异常'org.xml.sax.SAXParseException:意外的标记(位置:TEXT {“Data”:null,“Re ... @ 1:499 in java.io.InputStreamReader @ bc741c)' –

+0

@SakibSyed我已经用我已经试过的完整代码更新了答案 –

+0

@SakibSyed另外,在onPostExecute()中,您可以删除for循环并仅使用Node nNode = nodelist.item(0);请参见完整代码I已更新 –