简体   繁体   English

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

[英]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 : 基本上,我正在创建一个Android游戏,并希望将一些关卡数据保存在XML文件中,这些文件保存在资产文件夹中,我将其解析为:

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. 直到那时一切都还不错,我才能够成功创建和保存XML文件。 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 我能够通过使用类似的东西来创建XML(以String数据类型)

(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. 现在我很困惑,如果这是正确的,或者我应该如何以XML形式(或任何方便的形式)动态创建它,以及在哪里保存(可能是android中的内部或外部存储)应该是最好的。因为我尝试了许多代码片段,在此之后在Google上找到许多我的代码的很多东西可能是无用的,无法正常工作,但是如果您说我可以添加它。谢谢您的帮助。

try my code it parse the data from asset/url 试试我的代码,它解析资产/ 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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