2012-07-21 51 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(); 
    } 

    } 

}