简体   繁体   中英

Creating ,Writing and Reading an XML File in Android

Basically I'm creating an android game and want to save some data for levels in an XML file which are saved in assets folder and I parse them like :

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();

Things were right until then, I was successfully able to create and save XML files. But not too much, I also wanted to create a level editor. I was able to create the XML (in String datatype) by just using something like

(there are various "String +=" in different methods based upon call from the level editor activity/scene):

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

And I am pretty confused now If this is correct Or how should I create this dynamically in XML form (or any convinient form) and where to save(probably internal or external storage in android) should be best.Since I tried many code Fragments from finding many things on google much of my code after this may be useless and not working, but if you say i can add it.Thanks for your Help.

try my code it parse the data from 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());

    }
}

and use this like that

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM