2012-07-21 54 views
0

我試圖編寫一個應用程序,它從本地xml文件中讀取,並且需要一些幫助。我已經閱讀了這裏的一些文章以及google和youtube來讀取/寫入xml文件,但其中大部分文件都是在線文件。我正在尋找在Android本地讀/寫xml。到目前爲止,我認爲,我需要的步驟如下。在Android本地讀取XML

  1. 讀取XML文件。
  2. 將元素轉換爲字符串數組。
  3. 使用字符串數組填充列表。

我似乎無法得到第一個2的工作。我不是在尋找代碼,也不是尋找代碼的簡單方法。我真的想弄清楚這一點,但需要你們大家在這裏的一些指導。我真的無法找到一種方法來讀取XML文件。從我在這裏找到的,我需要將XML文件放在res/raw文件夾中,然後從那裏,我不太確定該怎麼做。我如何將它讀入數組?一旦我把這個東西運行起來,我會盡我所能發佈代碼,並希望幫助其他有類似問題的人。再次感謝!

+0

這可以幫助你http://stackoverflow.com/questions/2728064/parsing-local-xml-file-sax-in-android – HADEV 2012-07-21 01:02:03

回答

1

我終於得到它的工作就是我想要的,這裏是我試圖完成。對所有提供的答案,非常感謝!我拿走了你的每一個模式,並根據需要定製它。我絕不是一個android/java/xml專家,但這是我得到的,它的工作方式我想要!

public class MainActivity extends Activity { 

Spinner spinner; 
List<String> ingredient = new ArrayList<String>(); 
List<String> effect1 = new ArrayList<String>(); 
List<String> effect2 = new ArrayList<String>(); 
List<String> effect3 = new ArrayList<String>(); 
List<String> effect4 = new ArrayList<String>(); 

XmlResourceParser myXml; 
int eventType; 
String nodeValue; 

@Override 
public void onCreate(Bundle savedInstanceState) { 

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

    loadXml(); // Reads XML and loads it into Lists, One list for each element 
    convertListToSpinner(); // Takes Lists and merges data with Spinners (Currently Unimplemented) 


} 


private void convertListToSpinner() { 
    // TODO Auto-generated method stub 

} 


private void loadXml() { 
    // TODO Auto-generated method stub 
    myXml = getBaseContext().getResources().getXml(R.xml.xmlfilename); 
    try { 
     myXml.next(); 

    eventType = myXml.getEventType(); // Get current xml Event 

    } catch (XmlPullParserException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

    while(eventType != XmlPullParser.END_DOCUMENT){ 
     if(eventType == XmlPullParser.START_DOCUMENT){ 
      // checks can be placed here to make sure file is read 
     } 
     else if(eventType == XmlPullParser.START_TAG){ 
      nodeValue = myXml.getName(); 

      try{ 
      if(nodeValue.equalsIgnoreCase("Ingredient")){ //Finds Ingredient tag 
      myXml.next(); //Since the ingredient tag does not hold the text, we go to next element area 
      ingredient.add(myXml.getText().trim()); // Set the text of the Ingredient tag to list 
      } 

      //Since the effect tags are followed by ending tags, we can just do nextText() to get tag text 
      if(nodeValue.equalsIgnoreCase("Effect1")){ 
       effect1.add(myXml.nextText().trim()); // Set the text of the Effect1 tag to list 
      } 
      if(nodeValue.equalsIgnoreCase("Effect2")){ 
       effect2.add(myXml.nextText().trim()); // ditto 
      } 
      if(nodeValue.equalsIgnoreCase("Effect3")){ 
       effect3.add(myXml.nextText().trim()); // ditto 
      } 
      if(nodeValue.equalsIgnoreCase("Effect4")){ 
       effect4.add(myXml.nextText().trim()); // ditto 
      } 
      }catch(Exception e){ 
       e.getMessage(); 
      } 


     } 
     try { 
      eventType = myXml.next(); 
     } catch (XmlPullParserException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 

    for(int i = 0; ingredient.size() > i; i++){ 
     System.out.println(ingredient.get(i)); 

    } 

} 


@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    getMenuInflater().inflate(R.menu.activity_main, menu); 
    return true; 
} 




} 

而XML文件是以當前格式。

<?xml version="1.0" encoding="UTF-8"?> 
<resources xmlns:android="http://schemas.android.com/apk/res/android" > 
    <item 
     name="item" 
     type="string"> 
     <Ingredient> 
     Intrests 
      <effect1> 
      Android 
      </effect1> 
      <effect2> 
      Programming 
      </effect2> 
      <effect3> 
      Type O Negative 
      </effect3> 
      <effect4> 
      Sirenia 
      </effect4> 
     </Ingredient> 
     <Ingredient> 
     Virtues 
      <effect1> 
     Power 
      </effect1> 
      <effect2> 
     Money 
      </effect2> 
      <effect3> 
     Knowledge 
      </effect3> 
      <effect4> 
     Kindness 
      </effect4> 
     </Ingredient> 
    </item> 
</resources> 

我希望這可以幫助其他有類似問題的人。再次感謝Sobo和HADEV的貢獻!

我敢肯定有做的是做什麼工作的一種更好的方式,但我很高興我得到了這個工作:)

2

在主類

import android.app.Activity; 
import android.content.Intent; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.AdapterView; 
import android.widget.AdapterView.OnItemClickListener; 
import android.widget.ArrayAdapter; 
import android.widget.ListView; 
import android.widget.Toast; 

public class SimpleList extends Activity { //SimpleList is the name of this class 

    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     final ListView lv=(ListView)findViewById(R.id.listView1);  

     //final ArrayList<String> myNewList = new ArrayList<String>(); 

     ArrayAdapter<CharSequence> adapter=ArrayAdapter.createFromResource(this, R.array.simple_array,android.R.layout.simple_list_item_1); 
     lv.setAdapter(adapter); 
     lv.setOnItemClickListener(new OnItemClickListener() { 

      @Override 
      public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { 
       // TODO Auto-generated method stub  
       String item=lv.getItemAtPosition(arg2).toString(); 
       String itemordered; 
       itemordered = item + " added to list"; 
       Toast.makeText(getApplicationContext(), itemordered, Toast.LENGTH_LONG).show(); 
      } 
     }); 
    } 
} 

創建的strings.xml一個字符串數組

<resources> 

    <string name="app_name">SimpleList</string> 
    <string name="menu_settings">Settings</string> 
    <string name="title_activity_main">SimpleList</string> 

    <string-array name="simple_array"> 
     <item>Bacon Double Cheese Burger</item> 
     <item>Bacon Cheeses Burger</item> 
     <item>Cheese Burger</item> 
     <item>Hamburger</item> 
     <item>Grilled Chicken Sandwich</item> 
     <item>Crispy Chicken Sandwich</item> 
     <item>Chicken Strips</item> 
     <item>Hot Dog</item> 
     <item>Chocolate Chip Cookie Dough Polar Swirl</item> 
     <item>Vanilla Shake</item> 
     <item>Chocolate Shake</item> 
     <item>Strawberry Shake</item> 
    </string-array> 


</resources>  

main.xml中創建您的ListView佈局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="vertical" > 

    <ListView 
     android:id="@+id/listView1" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     android:divider="#FFCC00" 
     android:dividerHeight="2dp" > 
    </ListView> 

</LinearLayout> 
+0

哇,謝謝你的時間和信息。肯定有幫助! – 2012-07-21 01:09:47

2

可以使用SAX解析器

SAX回調方法:

startDocument()調用endDocument() - 調用的方法在XML文檔的開始和結束。 startElement()endElement() - 在文檔元素的開始和結束處調用的方法。 characters() - 使用XML文檔元素的開始和結束標記之間的文本內容調用的方法。

假設你有這樣的XML文件:解析

<?xml version="1.0"?> 
<company> 
    <staff> 
     <firstname>yong</firstname> 
     <lastname>mook kim</lastname> 
     <nickname>mkyong</nickname> 
     <salary>100000</salary> 
    </staff> 
    <staff> 
     <firstname>low</firstname> 
     <lastname>yin fong</lastname> 
     <nickname>fong fong</nickname> 
     <salary>200000</salary> 
    </staff> 
</company> 

java類:

import javax.xml.parsers.SAXParser; 
import javax.xml.parsers.SAXParserFactory; 
import org.xml.sax.Attributes; 
import org.xml.sax.SAXException; 
import org.xml.sax.helpers.DefaultHandler; 

public class ReadXMLFile { 

    public static void main(String argv[]) { 

    try { 

    SAXParserFactory factory = SAXParserFactory.newInstance(); 
    SAXParser saxParser = factory.newSAXParser(); 

    DefaultHandler handler = new DefaultHandler() { 

    boolean bfname = false; 
    boolean blname = false; 
    boolean bnname = false; 
    boolean bsalary = false; 

    public void startElement(String uri, String localName,String qName, 
       Attributes attributes) throws SAXException { 

     System.out.println("Start Element :" + qName); 

     if (qName.equalsIgnoreCase("FIRSTNAME")) { 
      bfname = true; 
     } 

     if (qName.equalsIgnoreCase("LASTNAME")) { 
      blname = true; 
     } 

     if (qName.equalsIgnoreCase("NICKNAME")) { 
      bnname = true; 
     } 

     if (qName.equalsIgnoreCase("SALARY")) { 
      bsalary = true; 
     } 

    } 

    public void endElement(String uri, String localName, 
     String qName) throws SAXException { 

     System.out.println("End Element :" + qName); 

    } 

    public void characters(char ch[], int start, int length) throws SAXException { 

     if (bfname) { 
      System.out.println("First Name : " + new String(ch, start, length)); 
      bfname = false; 
     } 

     if (blname) { 
      System.out.println("Last Name : " + new String(ch, start, length)); 
      blname = false; 
     } 

     if (bnname) { 
      System.out.println("Nick Name : " + new String(ch, start, length)); 
      bnname = false; 
     } 

     if (bsalary) { 
      System.out.println("Salary : " + new String(ch, start, length)); 
      bsalary = false; 
     } 

    } 

    }; 

     saxParser.parse("c:\\file.xml", handler); 

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

    } 

}