解析xml时没有得到输出

时间:2012-04-26 05:24:52

标签: android xml-parsing response

我正在使用soap webservice并且我得到了正确的响应,现在我想解析我为此编写代码的响应,但我没有得到输出,有人可以帮助我吗?

我的主要课程是

public class Mylearning extends ListActivity {
    //ArrayList<cat> list = null;
    private static final String SOAP_ACTION="http://yyy.mobi/GetLearningPortalsList";
    private static final String METHOD_NAME ="GetLearningPortalsList";
    private static final String NAMESPACE ="http://yyy.mobi/";
    private static final String URL = "http://webservices.yyy.mobi/MobileLMSServices.asmx";
    private Bundle bundleResult = new Bundle();
    private JSONObject JSONObj;
    private JSONArray JSONArr;
    //private ArrayList<HashMap<String, Object>> myList;
    SoapObject request;
    TextView tv;
    TextView tv1;
    TextView tv2;               
    ListView mainListView;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mylearning);

        //mainListView = (ListView) findViewById(R.id.main_listview);
        request = new SoapObject(NAMESPACE, METHOD_NAME);
        request.addProperty("SiteURL","http://www.yyy.mobi/");
        request.addProperty("PageID","1");
        request.addProperty("SearchText","");

        ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();   

        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.dotNet = true;
        SoapObject result = null;
        envelope.setOutputSoapObject(request);
        AndroidHttpTransport sab = new AndroidHttpTransport(URL);
        sab.debug = true;
        try {
            sab.call(SOAP_ACTION, envelope);
            if (envelope.getResponse() != null) {
                result = (SoapObject) envelope.bodyIn;
                String[] values = new String[result.getPropertyCount()];
                int j = result.getPropertyCount();
                String repons=result.toString();
            //  Log.d("result",repons.toString());
                Document doc = XMLfunctions.XMLfromString(repons);
                int numResults = XMLfunctions.numResults(doc);

                if((numResults <= 0)){
                    Toast.makeText(Mylearning.this, "Geen resultaten gevonden", Toast.LENGTH_LONG).show();  
                    finish();
                }

                 NodeList nodes = doc.getElementsByTagName("result");
                for (int i = 0; i < nodes.getLength(); i++) {                           
                    HashMap<String, String> map = new HashMap<String, String>();
                    Element e = (Element)nodes.item(i);
                    map.put("Course", XMLfunctions.getValue(e, "Course"));
                    map.put("Description", "Description:" + XMLfunctions.getValue(e, "Description"));
                    map.put("icon", "icon: " + XMLfunctions.getValue(e, "icon"));
                    mylist.add(map);            
                }

                ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.rowmylearning, 
                        new String[] { "Course", "Description","icon" }, 
                        new int[] { R.id.txt1, R.id.txt2,R.id.img1 });

                setListAdapter(adapter);
                final ListView lv = getListView();

                lv.setTextFilterEnabled(true);  
                lv.setOnItemClickListener(new OnItemClickListener() {
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {              
                        @SuppressWarnings("unchecked")
                        HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);                   
                        Toast.makeText(Mylearning.this, "Course '" + o.get("Course") + "' was clicked.", Toast.LENGTH_LONG).show(); 

                    }
                });

            }
        }

                catch (Exception e) {
                    e.printStackTrace();
                }

            }
}

我的XMLFunction类是

public class XMLfunctions {

    public final static Document XMLfromString(String repons){

        Document doc = null;

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder db = dbf.newDocumentBuilder();
            InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(repons));
            Log.d("message",repons.toString());
            doc = db.parse(is);
        } catch (ParserConfigurationException e) {
            System.out.println("XML parse error: " + e.getMessage());
            return null;
        } catch (SAXException e) {
            System.out.println("Wrong XML file structure: " + e.getMessage());
            return null;
        } catch (IOException e) {
            System.out.println("I/O exeption: " + e.getMessage());
            return null;
        }

        return doc;

    }

    /** Returns element value
      * @param elem element (it is XML tag)
      * @return Element value otherwise empty String
      */
     public final static String getElementValue( Node elem ) {
         Node kid;
         if( elem != null){
             if (elem.hasChildNodes()){
                 for( kid = elem.getFirstChild(); kid != null; kid = kid.getNextSibling() ){
                     if( kid.getNodeType() == Node.TEXT_NODE  ){
                         return kid.getNodeValue();
                     }
                 }
             }
         }
         return "";
     }
    public static int numResults(Document doc){     
        Node results = doc.getDocumentElement();
        int res = -1;

        try{
            res = Integer.valueOf(results.getAttributes().getNamedItem("count").getNodeValue());
        }catch(Exception e ){
            res = -1;
        }

        return res;
    }

public static String getValue(Element item, String str) {       
    NodeList n = item.getElementsByTagName(str);        
    return XMLfunctions.getElementValue(n.item(0));
}

}

我的回复如下

 04-25 11:53:32.806: D/status(2924): GetLearningPortalsListResponse{GetLearningPortalsListResult=anyType{schema=anyType{element=anyType{complexType=anyType{choice=anyType{element=anyType{complexType=anyType{sequence=anyType{element=anyType{}; element=anyType{}; element=anyType{}; element=anyType{}; element=anyType{}; element=anyType{}; }; }; }; element=anyType{complexType=anyType{sequence=anyType{element=anyType{}; }; }; }; }; }; }; }; 
diffgram=anyType
{
NewDataSet=anyType

{
Table=anyType
{
ROWID=1; SiteID=7; PortalName=Pinneast; mSiteURL=http://pinneast.xxx.mobi/; ProtalLogo=/Content/SiteConfiguration/7/MyportalLogo.gif; Description=Pinneast is focused on improving business performance through human capital development and experienced in helping organizations of all sizes and across all industries; 
};

Table=anyType   
{
ROWID=2; SiteID=10; PortalName=Coach Institute; mSiteURL=http://coachinstitute.xxx.mobi/; ProtalLogo=/Content/SiteConfiguration/10/MyportalLogo.gif; Description=The Coaching Institute, where you are learning from someone who “does” and not just someone who “teaches”. We can train you to be a successful coach.; 
}; 

Table=anyType
{
ROWID=3; SiteID=12; PortalName=Ready Courses; mSiteURL=http://readycourses.xxx.mobi/; ProtalLogo=/Content/SiteConfiguration/12/MyportalLogo.gif; Description=When you work with us, you get a professional team of e-learning and corporate training professionals who are passionate about getting the best technology implemented without high costs.; 
}; 

Table=anyType
{
ROWID=4; SiteID=13; PortalName=A Step to Gold; mSiteURL=http://asteptogold.xxx.mobi/; ProtalLogo=/Content/SiteConfiguration/13/MyportalLogo.gif; 
Description=The Ballroom is solely owned and operated by Melanie Dale. It has a 2400 square foot floating floor, and two other teaching studios.; 
}; 


Table=anyType
{ROWID=5; SiteID=14; PortalName=In Sync Training; mSiteURL=http://insynctraining.xxx.mobi/; ProtalLogo=/Content/SiteConfiguration/14/MyportalLogo.gif; 
Description=InSync Training offers a variety of consulting, development and delivery services to support synchronous training initiatives.; 
}; 

Table=anyType
{ROWID=6; SiteID=15; PortalName=Total Motion Release; mSiteURL=http://totalmotionrelease.xxx.mobi/; ProtalLogo=/Content/SiteConfiguration/15/MyportalLogo.gif;
 Description=Two stories emphasize how Tom Dalonzo-Baker discovered Total Motion Release.; }; 

Table=anyType
{ROWID=7; SiteID=16; PortalName=Polaris Consultants; mSiteURL=http://polaris.xxx.mobi/; ProtalLogo=/Content/SiteConfiguration/16/MyportalLogo.gif; 
Description=Founded in 1997, and located adjacent to the Research Triangle Park in North Carolina, Polaris Clinical Research Consultants, Inc.; };

Table=anyType
{ROWID=8; SiteID=17; 
PortalName=Develop Mentor Training; mSiteURL=http://developmentor.xxx.mobi/; ProtalLogo=/Content/SiteConfiguration/17/MyportalLogo.gif; Description=DevelopMentor provides in-depth, hands-on training for experienced developers.; }; 


Table=anyType
{ROWID=9; SiteID=18; PortalName=Cranky Middle Manager; mSiteURL=http://cmm.xxx.mobi/; ProtalLogo=/Content/SiteConfiguration/18/MyportalLogo.gif; 
Description=If you've ever felt like you're trapped between the idiots who make the decisions and the morons who won't do as their told.; };

Table=anyType
{ROWID=10; SiteID=19; 
PortalName=ITPreneurs; mSiteURL=http://itpreneurs.xxx.mobi/; ProtalLogo=/Content/SiteConfiguration/19/MyportalLogo.gif; 
Description=ITpreneurs is the leading training solutions company in the IT management and IT governance best practices domain.;
 }; 
Table1=anyType{TotalRecordsCount=387; }; 
}; 
}; 
}; 
}

2 个答案:

答案 0 :(得分:0)

你的xml.have中有你的计数标签吗?

因为在numResults中function.it根据xml中的count标签返回结果。

答案 1 :(得分:0)

此代码解析来自Web服务的XML数据。它有效。

  super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_servis_uygulamasi);

    Button btn=(Button)findViewById(R.id.button1);   

    btn.setOnClickListener(new View.OnClickListener()
    {    
          public void onClick(View v)
          {
            String pSoapAction  = "http://tempuri.org/GetMagazaList";
            String pMethodName  = "GetMagazaList";
            String pNameSpace   = "http://tempuri.org/";
            String pUrl         ="";

            SoapObject result =(SoapObject)getWebServisDATA(pUrl, pMethodName, pNameSpace, pSoapAction, "333");

            TextView   tv =(TextView)findViewById(R.id.textView2);

            try
            {                                                                              
                               SoapObject soapObjectGetProperty=(SoapObject)result.getProperty(0);

                               SoapObject resDiff  = (SoapObject)soapObjectGetProperty.getProperty("diffgram");
                              SoapObject resDocEl = (SoapObject)resDiff.getProperty("DocumentElement");


                               StringBuilder stringBuilder = new StringBuilder();


         for(int j=0;j<resDocEl.getPropertyCount();j++)
         {
            SoapObject resTable= (SoapObject)resDocEl.getProperty(j);

            String MagazaObjId      =resTable.getProperty("MagazaObjId").toString();
            String MagazaAdi        = resTable.getProperty("MagazaAdi").toString();
            String MagazaKodu       = resTable.getProperty("MagazaKodu").toString();
           String MagazaPosDepoNo  =resTable.getProperty("MagazaPosDepoNo").toString();
           String PosId            = resTable.getProperty("PosId").toString();
           String IsYeriObjId      = resTable.getProperty("IsYeriObjId").toString();                                   

           stringBuilder.append
           (                                             
              "MagazaObjId     :" +MagazaObjId+"\n"+
              "MagazaAdi       :"  +MagazaAdi+"\n"+
              "MagazaKodu      :" +MagazaKodu+"\n"+
              "MagazaPosDepoNo :"+MagazaPosDepoNo+"\n"+
              "PosId           :" +PosId+"\n"+
              "Type            :" +IsYeriObjId+"\n"+
              "******************************"
           );

           stringBuilder.append("\n");                                       
       }                                 
     tv.setText(stringBuilder);                                             
                       }
                       catch(Exception e)
                       {
                              tv.setText(e.getMessage());
                       }
                }
         });


}

public static SoapObject getWebServisDATA(String pUrl, String pMethodName,String pNameSpace, String pSoapAction,String pname) 
{
  SoapObject result = null;
  SoapObject request = new SoapObject(pNameSpace, pMethodName);
  SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
              SoapEnvelope.VER11);
  envelope.dotNet = true;
  request.addProperty("firma",pname);
  envelope.setOutputSoapObject(request);

  AndroidHttpTransport httpTransport = new AndroidHttpTransport(pUrl);

  try {
        httpTransport.call(pSoapAction, envelope);
        result = (SoapObject)envelope.bodyIn;
  } 
  catch (Exception e)
  {

  }

  return result;

}