在Android中创建,编写和读取XML文件

时间:2013-04-13 04:30:08

标签: android xml

基本上我正在创建一个Android游戏,并希望在XML文件中保存一些数据,这些数据保存在assets文件夹中,我解析它们如下:

final SAXParserFactory spf = SAXParserFactory.newInstance();
final SAXParser sp = spf.newSAXParser();
final XMLReader xmlReader = sp.getXMLReader();
final XMLParser pXMLParser = new XMLParser();//My own created Class
xmlReader.setContentHandler(pXMLParser);
InputStream inputStream = Z.act.getAssets().open("levels/" + PackName + ".xml");
xmlReader.parse(new InputSource(new BufferedInputStream(inputStream)));
return pXMLParser.getParsedLevel();

直到那时事情才对,我成功地创建并保存了XML文件。但不是太多,我也想创建一个关卡编辑器。我能够创建XML (使用String数据类型)只需使用类似

的内容

(基于来自关卡编辑器活动/场景的调用,在不同的方法中有各种“String + =”):

String XMLString = "";
XMLString += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
....
XMLString += " </" + tagEnemy + ">"; // tagEnemy is a variable string I created

我现在非常困惑如果这是正确的或者我应该如何以XML格式(或任何方便的形式)动态创建它,哪里保存(可能是android中的内部或外部存储)应该是最好的。因为我尝试了很多代码片段在google上找到很多东西之后的代码可能是没用的而且没有用,但如果你说我可以添加它。谢谢你的帮助。

1 个答案:

答案 0 :(得分:1)

尝试我的代码,它解析来自asset / url的数据

public class SaxParserTest extends DefaultHandler {
    Boolean currentElement = false;
    String currentValue = null;
    ArrayList<HashMap<String, Object>> datalist = new ArrayList<HashMap<String, Object>>();
    HashMap<String, Object> temp;
    public ArrayList<HashMap<String, Object>> getData(Context context ){
        try {
            SAXParserFactory saxparser = SAXParserFactory.newInstance();
            SAXParser parser = saxparser.newSAXParser();
            XMLReader xmlReader = parser.getXMLReader();
            xmlReader.setContentHandler(SaxParserTest.this);
            /*
             * used when pick local data
             */
//              InputStream is =context.getAssets().open("data.xml");
//              xmlReader.parse(new InputSource(is));
            /*
             * used when pick data from url
             */
            URL url = new URL("http://www.xmlfiles.com/examples/cd_catalog.xml");
            xmlReader.parse(new InputSource(url.openStream()));     
        } catch (Exception e) {
            e.getMessage();
        }
        return datalist;
    }

    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
        super.startElement(uri, localName, qName, attributes);
        if (localName.equalsIgnoreCase("CD")) {
            temp=new HashMap<String, Object>();
            temp.put(Constant.id, attributes.getValue(Constant.id));
//          temp.put(Constant.title, attributes.getValue(Constant.title));
//          temp.put(Constant.artist, attributes.getValue(Constant.artist));
//          temp.put(Constant.country, attributes.getValue(Constant.country));
//          temp.put(Constant.company, attributes.getValue(Constant.company));
//          temp.put(Constant.price, attributes.getValue(Constant.price));
//          temp.put(Constant.year, attributes.getValue(Constant.year));
        }
    }

    @Override
    public void characters(char[] ch, int start, int length)
            throws SAXException {
        super.characters(ch, start, length);
            currentValue = new String(ch, start, length);
    }

    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {
        super.endElement(uri, localName, qName);
        if(localName.equals(Constant.title))
        temp.put(Constant.title, currentValue);
        if(localName.equals(Constant.artist))
        temp.put(Constant.artist, currentValue);
        if(localName.equals(Constant.country))
        temp.put(Constant.country, currentValue);
        if(localName.equals(Constant.company))
        temp.put(Constant.company, currentValue);
        if(localName.equals(Constant.price))
        temp.put(Constant.price, currentValue);
        if(localName.equals(Constant.year))
        temp.put(Constant.year, currentValue);
        if(localName.equalsIgnoreCase("CD"))
            datalist.add(temp);
        Log.i("DataList", datalist.toString());

    }
}

并像这样使用

SaxParserTest test=new SaxParserTest();
            datal=test.getData(this);
            SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, datal,
                    R.layout.activity_main, new String[] { Constant.title,
                            Constant.artist, Constant.price, Constant.year,
                            Constant.company, Constant.country ,Constant.id}, new int[] {
                            R.id.txt1, R.id.txt2, R.id.txt3, R.id.txt4,
                            R.id.txt5, R.id.txt6 ,R.id.txt7});
            setListAdapter(adapter);