如何写入XML文件?

时间:2011-07-10 11:15:07

标签: android xml xmlpullparser

我在资产文件夹中有一个“config.xml”文件。我使用以下代码从中读取:

public static String readAppConfigKey(Context context, String section,
        String key) {
    String value = "";
    AssetManager assetManager = context.getAssets();

    InputStream istr;
    try {
        istr = assetManager.open("config.xml");
        XmlPullParserFactory factory;
        factory = XmlPullParserFactory.newInstance();
        factory.setNamespaceAware(true);
        XmlPullParser xmlParser = factory.newPullParser();
        xmlParser.setInput(istr, "UTF-8");

        String strPrevElement = "";
        String strElement = "";
        String strKey = "";

        xmlParser.next();
        int eventType = xmlParser.getEventType();
        while (eventType != XmlResourceParser.END_DOCUMENT) {
            if (eventType == XmlResourceParser.START_TAG) {
                if (xmlParser.getName().compareTo(strElement) != 0) {
                    // after any change
                    strPrevElement = strElement;
                    strElement = xmlParser.getName();
                }
                strKey = xmlParser.getAttributeValue(null, "key");
                if (strPrevElement.compareTo(section) == 0
                        && strKey != null && strKey.compareTo(key) == 0) {
                    value = xmlParser.getAttributeValue(null, "value");
                    return value;
                }
            }
            eventType = xmlParser.next();
        }
    } catch (XmlPullParserException e) {

    } catch (IOException e) {

    }
    return value;
}

如何使用XmlPullParser写入?

谢谢,

2 个答案:

答案 0 :(得分:2)

我不相信你可以写资产文件夹中的文件。我想你必须将它复制到SD卡并在那里读写它。

另外,XmlPullParser只读取XML,不写入。请查看本教程,了解如何修改XML:

How to modify XML file in Java

答案 1 :(得分:0)

如果具有InputStream,则具有文件的字节,如果具有文件的字节,则将它们写入磁盘(:

        //1. Convert the inputStream to Byte Array
        InputStream inputStream = . . .

        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        int nRead;
        byte[] data = new byte[Integer.MAX_VALUE]; //need to make sure here that the inputstream is less then 2g (Integer.MAX_VALUE), in case its bigger file we will need to read and write in parts
        while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
            buffer.write(data, 0, nRead);
        }
        buffer.flush();

        byte[] xmlFileBytes = buffer.toByteArray();

        //2.  write the bytes to file
        String filePath = "file.xml";
        File file = new File(filePath);
        FileOutputStream outputStream = new FileOutputStream(file);
        outputStream.write(xmlFileBytes);
        outputStream.close();