2

我正在从 URL 解析 XML。从原始文件夹中解析相同的 XML 文件进行了哪些更改。对如何减少代码有任何想法吗?

这是我的 xml 文件:umesh.xml

<?xml version="1.0" encoding="utf-8"?>
<appdata>
<brand name="Lovely Products">
<product>Hat</product>
<product>Gloves</product>
</brand>
<brand name="Great Things">
<product>Table</product>
<product>Chair</product>
<product>Bed</product>
</brand>
</appdata> 

下面是我的java文件:

  1. 数据处理程序.java

    package com.umesh.xmlparsing;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.URL;
    import java.net.URLConnection;
    import java.util.ArrayList;
    
    import javax.xml.parsers.SAXParser;
    import javax.xml.parsers.SAXParserFactory;
    
    import org.xml.sax.Attributes;
    import org.xml.sax.InputSource;
    import org.xml.sax.SAXException;
    import org.xml.sax.XMLReader;
    import org.xml.sax.helpers.DefaultHandler;
    
    import android.content.Context;
    import android.content.res.XmlResourceParser;
    import android.graphics.Color;
    import android.util.Log;
    import android.widget.TextView;
    
    
    
    public class DataHandler extends DefaultHandler{
    
    //list for imported product data
    private ArrayList<TextView> theViews;
    //string to track each entry
    private String currBrand = "";
    //flag to keep track of XML processing
    private boolean isProduct = false;
    //context for user interface
    private Context theContext;
    //constructor
    public DataHandler(Context cont) {
        super();
        theViews = new ArrayList<TextView>();
        theContext = cont;
    }
    
    
    //start of the XML document
    public void startDocument () { Log.i("DataHandler", "Start of XML document"); }
    
    //end of the XML document
    public void endDocument () { Log.i("DataHandler", "End of XML document"); }
    
    //opening element tag
    public void startElement (String uri, String name, String qName, Attributes atts)
    {
        //handle the start of an element
    
        //find out if the element is a brand
        if(qName.equals("brand"))
        {
            //set product tag to false
            isProduct = false;
            //create View item for brand display
            TextView brandView = new TextView(theContext);
            brandView.setTextColor(Color.rgb(73, 136, 83));
            //add the attribute value to the displayed text
            String viewText = "Items from " + atts.getValue("name") + ":";
            brandView.setText(viewText);
            //add the new view to the list
            theViews.add(brandView);
        }
        //the element is a product
        else if(qName.equals("product"))
            isProduct = true;
    }
    
    //closing element tag
    public void endElement (String uri, String name, String qName)
    {
        //handle the end of an element
        if(qName.equals("brand"))
        {
            //create a View item for the products
            TextView productView = new TextView(theContext);
            productView.setTextColor(Color.rgb(192, 199, 95));
            //display the compiled items
            productView.setText(currBrand);
            //add to the list
            theViews.add(productView);
            //reset the variable for future items
            currBrand = "";
        }
    }
    
    //element content
    public void characters (char ch[], int start, int length)
    {
        //process the element content
        //string to store the character content
        String currText = "";
        //loop through the character array
        for (int i=start; i<start+length; i++)
        {
            switch (ch[i]) {
            case '\\':
                break;
            case '"':
                break;
            case '\n':
                break;
            case '\r':
                break;
            case '\t':
                break;
            default:
                currText += ch[i];
                break;
            }
        }
        //prepare for the next item
        if(isProduct && currText.length()>0)
            currBrand += currText+"\n";
    }
    
    public ArrayList<TextView> getData()
    {
        //take care of SAX, input and parsing errors
        try
        {
                //set the parsing driver
            System.setProperty("org.xml.sax.driver","org.xmlpull.v1.sax2.Driver");
                //create a parser
            SAXParserFactory parseFactory = SAXParserFactory.newInstance();
            SAXParser xmlParser = parseFactory.newSAXParser();
                //get an XML reader
            XMLReader xmlIn = xmlParser.getXMLReader();
                //instruct the app to use this object as the handler
            xmlIn.setContentHandler(this);
                //provide the name and location of the XML file **ALTER THIS FOR YOUR FILE**
            URL xmlURL = new URL("http://mydomain.com/umesh.xml");
    
    
                //open the connection and get an input stream
            URLConnection xmlConn = xmlURL.openConnection();
            InputStreamReader xmlStream = new InputStreamReader(xmlConn.getInputStream());
    
                //build a buffered reader
            BufferedReader xmlBuff = new BufferedReader(xmlStream);
    
            //   uuu   XmlResourceParser todolistXml = getResources().getXml(R.raw.c4mh_clinics);
                //parse the data
            xmlIn.parse(new InputSource(xmlBuff));
        }
        catch(SAXException se) { Log.e("AndroidTestsActivity", 
                "SAX Error " + se.getMessage()); }
        catch(IOException ie) { Log.e("AndroidTestsActivity", 
                "Input Error " + ie.getMessage()); }
        catch(Exception oe) { Log.e("AndroidTestsActivity", 
                "Unspecified Error " + oe.getMessage()); }
            //return the parsed product list
        return theViews;
    }
    
    }
    
  2. XMLParsing.java

    package com.umesh.xmlparsing;
    
    import java.util.ArrayList;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.widget.LinearLayout;
    import android.widget.TextView;
    
    public class XMLParsing extends Activity {
    
    TextView tv;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        //get a reference to the layout
        LayoutInflater inflater = getLayoutInflater();
        LinearLayout mainLayout = (LinearLayout) inflater.inflate(R.layout.main,null);
        try
        {
                //create an instance of the DefaultHandler class 
                //**ALTER THIS FOR YOUR CLASS NAME**
            DataHandler handler = new DataHandler(getApplicationContext());
                //get the string list by calling the public method
            ArrayList<TextView> newViews = handler.getData();
                //convert to an array
            Object[] products = newViews.toArray();
                //loop through the items, creating a View item for each
            for(int i=0; i<products.length; i++)
            {
                //add the next View in the list
                mainLayout.addView((TextView)products[i]);
            }
        }
        catch(Exception pce) { Log.e("AndroidTestsActivity", "PCE "+pce.getMessage()); }
    
        setContentView(mainLayout);
    }
    
    
    }
    
4

1 回答 1

1

请参阅我的答案的以下链接,它将解决您的问题。

本地 XML 解析

于 2012-10-17T07:18:46.820 回答