0

我正在尝试解析一个非常基本的 XML 文件,如下所示:

<xml>
  <customer>
    <CustID>10</CustID>
    <custvar1>10</custvar1>
    <custvar2>10</custvar2>
    <custvar3>10</custvar3>
  </customer>
</xml>

我基本上没有得到任何结果。离开我做的最后一个应用程序,无论出于何种原因,它都不会给我任何错误。我今天花了 8 个小时在这上面,所以任何帮助都将不胜感激。我也不完全确定我在解析什么,我有一个大致的了解,但没有什么比这更可靠的了。

我把它分成两个线程,或者至少我相信我有。我只是在寻找所有这些代码出错的地方。任何帮助是极大的赞赏!!

我提前感谢大家的帮助!!

这是代码:

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Xml;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

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

    final Button getData = (Button) findViewById(R.id.getData);
    getData.setOnClickListener(new View.OnClickListener(){
        public void onClick(View v) {

            background();

            Toast toast = Toast.makeText(getApplicationContext(), "Toast 1", Toast.LENGTH_SHORT);
            toast.show();
        }
    });
}

public class Customer
{
    public final String custID;
    public final String var1;
    public final String var2;
    public final String var3;

    private Customer()
    {
        custID = null;
        var1 = null;
        var2 = null;
        var3 = null;
    }

    private Customer(String custID, String var1, String var2, String var3)
    {
        this.custID = custID;
        this.var1 = var1;
        this.var2 = var2;
        this.var3 = var3;

    }
}

private Customer readCustomer(XmlPullParser parser) throws XmlPullParserException, IOException
{
    parser.require(XmlPullParser.START_TAG, null, "customer");
    String custID = null;
    String var1 = null;
    String var2 = null;
    String var3 = null;

    while(parser.next() != XmlPullParser.END_TAG)
    {
        if (parser.getEventType() != XmlPullParser.START_TAG)
        {
            continue;
        }
        String name = parser.getName();
        if (name.equals("CustID"))
        {
            custID = readCustID(parser);
        } else if (name.equals("custvar1"))
        {
            var1 = readVar1(parser);
        } else if (name.equals("custvar2"))
        {
            var2 = readVar2(parser);
        } else if (name.equals("custvar3"))
        {
            var3 = readVar3(parser);
        } else
        {
            skip(parser);
        }

    }
    return new Customer(custID, var1, var2, var3);
}

private String readCustID(XmlPullParser parser) throws IOException, XmlPullParserException
{
    parser.require(XmlPullParser.START_TAG, null, "CustID");
    final String custID = readText(parser);
    parser.require(XmlPullParser.END_TAG, null, "CustID");

    final Handler handler;
    handler = new Handler();

    handler.post(new Runnable() {
        public void run()
        {
            //Display toast
            Toast toast = Toast.makeText(getApplicationContext(), "ID: " + custID, Toast.LENGTH_SHORT);
            toast.show();
        }
    });

    return custID;
}

private String readVar1(XmlPullParser parser) throws IOException, XmlPullParserException
{
    parser.require(XmlPullParser.START_TAG, null, "CustID");
    String var1 = readText(parser);
    parser.require(XmlPullParser.END_TAG, null, "CustID");
    return var1;
}

private String readVar2(XmlPullParser parser) throws IOException, XmlPullParserException
{
    parser.require(XmlPullParser.START_TAG, null, "CustID");
    String var2 = readText(parser);
    parser.require(XmlPullParser.END_TAG, null, "CustID");
    return var2;
}

private String readVar3(XmlPullParser parser) throws IOException, XmlPullParserException
{
    parser.require(XmlPullParser.START_TAG, null, "CustID");
    String var3 = readText(parser);
    parser.require(XmlPullParser.END_TAG, null, "CustID");
    return var3;
}

private String readText(XmlPullParser parser) throws IOException, XmlPullParserException
{
    String result = "";
    if (parser.next() == XmlPullParser.TEXT)
    {
        result = parser.getText();
        parser.nextTag();
    }
    return result;
}

private void skip(XmlPullParser parser) throws IOException, XmlPullParserException
{
    if (parser.getEventType() != XmlPullParser.START_TAG)
    {
        throw new IllegalStateException();
    }
    int depth = 1;
    while (depth != 0)
    {
        switch (parser.next()) {
        case XmlPullParser.END_TAG:
            depth --;
        case XmlPullParser.START_TAG:
            depth++;
            break;
        }
    }
}

public class XMLparser
{       
    public Customer parse(InputStream in) throws XmlPullParserException, IOException {
        try
        {
            XmlPullParser parser = Xml.newPullParser();
            parser.setInput(in, null);
            parser.nextTag();
            return readXML(parser);
        } finally {
            in.close();
        }
    }

    private Customer readXML(XmlPullParser parser) throws XmlPullParserException, IOException
    {
        Customer custData = new Customer();

        parser.require(XmlPullParser.START_TAG, null, "xml");
        while (parser.next() != XmlPullParser.END_TAG)
        {
            if (parser.getEventType() != XmlPullParser.START_TAG)
            {
                continue;
            }
            String name = parser.getName();

            //Look for customer tag
            if (name.equals("customer"))
            {
                custData = readCustomer(parser);
            }
            else
            {
                skip(parser);
            }
        }

        return custData;
    }
}

private InputStream downloadUrl(String urlString) throws IOException
{
    URL url = new URL(urlString);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setReadTimeout(10000);
    conn.setConnectTimeout(15000);
    conn.setRequestMethod("GET");
    conn.setDoInput(true);

    //start the query
    conn.connect();
    InputStream stream = conn.getInputStream();
    return stream;
}

private void background()
{
    new Thread(new Runnable() {
        public void run(){
            //Delcare handler to allow UI modifications
            final Handler handler;
            handler = new Handler();

            final TextView TextVar1 = (TextView) findViewById(R.id.custvar1);
            final TextView TextVar2 = (TextView) findViewById(R.id.custvar2);
            final TextView TextVar3 = (TextView) findViewById(R.id.custvar3);

            InputStream stream = null;
            String URL = "***removed***";

            final TextView TextError = (TextView) findViewById(R.id.error);

            Customer customer = new Customer(null,null,null,null);
            XMLparser xmlParser = new XMLparser();

            try
            {
                stream = downloadUrl(URL);
                customer = xmlParser.parse(stream);
            }
            catch (IOException e)
            {
                TextError.setText(getResources().getString(R.string.connection_error));
            }
            catch (XmlPullParserException e)
            {
                TextError.setText(getResources().getString(R.string.connection_error));
            }
            finally
            {
                try {
                    stream.close();
                } catch (IOException e) {
                    //
                }
            }

            final Customer data = customer;

            handler.post(new Runnable() {                   
                public void run()
                {
                    //Display toast
                    Toast toast = Toast.makeText(getApplicationContext(), "Toast 2", Toast.LENGTH_SHORT);
                    toast.show();

                    //Set Text Views to show data
                    TextVar1.setText(data.var1);
                    TextVar2.setText(data.var2);
                    TextVar3.setText(data.var3);
                }
            });

        }

    });

}

}

4

2 回答 2

0

一开始,XML的常规格式应该是这样的,

    <?xml version="1.0"?>
   <customer>
    <CustID>10</CustID>
    <custvar1>10</custvar1>
    <custvar2>10</custvar2>
    <custvar3>10</custvar3>
  </customer>

然后,您必须设置以下 TO-Do 程序来读取 xml

  1. 创建文件流

  2. 创建文档实例

  3. 从源解析文件

  4. 提取具有条件的特定节点

  5. 读取并遍历步骤 4 中定义的所有节点。

你最好阅读这个以获得更多参考

于 2012-12-18T02:58:01.210 回答
0

嗨,试试这个代码,你肯定会得到输出..

public class TaplistingParser 
{
    public TaplistingParser()
    {

    }

    public String getXmlFromUrl(String url)
    {
        String xml=null;
        DefaultHttpClient httpclient=new DefaultHttpClient();
        HttpPost httpPost=new HttpPost(url);
        try 
        {
            HttpResponse httpresponse = httpclient.execute(httpPost);
            HttpEntity httpentity=httpresponse.getEntity();
            xml=EntityUtils.toString(httpentity);
        } 
        catch (ClientProtocolException e) 
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
        catch (IOException e) 
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
//      System.out.println("xml="+xml);
        return xml;
    }

    public Document getDomElement(String xml)
    {
        Document doc=null;
        DocumentBuilderFactory dbf= DocumentBuilderFactory.newInstance();
        dbf.setCoalescing(true);
        try 
        {
            DocumentBuilder db= dbf.newDocumentBuilder();

            InputSource is= new InputSource();
            is.setCharacterStream(new StringReader(xml));
            try {
                doc=db.parse(is);
            } catch (SAXException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } 
        catch (ParserConfigurationException e) 
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }       
        return doc;

    }

     public final String getElementValue( Node elem ) {
         Node child;
         if( elem != null){
             if (elem.hasChildNodes()){
                 for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
//                   if( child.getNodeType() == Node.TEXT_NODE  ){
                         return child.getNodeValue();
//                   }
                 }
             }
         }
         return "";
     }

     /**
      * Getting node value
      * @param Element node
      * @param key string
      * */
     public String getValue(Element item, String str) {     
            NodeList n = item.getElementsByTagName(str);        
            return this.getElementValue(n.item(0));
        }
}
于 2012-12-18T04:30:40.787 回答