2012-10-17 46 views
2

我正在解析来自URL的XML。从原始文件夹解析相同的XML文件做了哪些更改。有任何想法如何减少代码?从本地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. DataHandler.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); 
    } 
    
    
    } 
    
+0

Umesh制作,您应该保存在一个自定义类数据。一个textview有内部变量,但会占用内存,尽管你不需要它。你有没有尝试过一个ListView?它会显着减少你的代码。 – st0le

+0

这段代码从url读取xml,你可以编辑我的代码,以便它可以从本地原始文件夹中读取。 –

+0

只需使用xmlIn.parse(getResources())来重新编译'xmlIn.parse(new InputSource(xmlBuff));'。 openRawresource(id));'不确定parse是否有一个InputStream参数化的重载函数,但这是主要的。 – st0le

回答

1

请参阅我的回答如下的链接,它会解决你的问题。

Local XML Parsing

+0

它适用于我......我只是改变一行.. InputStream = res.openRawResource(R.raw.localxmlfileName); InputStream is = getResources()。openRawResource(R.raw.localxmlfileName);因为res字不解决。我不知道为什么..但最后完成..非常感谢..这是非常简单的代码,并减少编码... –

+0

但它显示输出为帽子表。我想在第一组产品和第二组产品下面展示产量。 –