你的位置:首页 > 操作系统

[操作系统]Android 解析XML文件和生成XML文件


解析

public static void init//can't create in /data/media/0 because permission     //can create in /sdcard/hotel    File mSettings = new File(HOTEL_PATH_if (!mSettings.exists()) {      mSettings.mkdirs();    }    File settings = new File(mSettings,"settings.");    Log.i("", settings+"+1+");    if (!settings.exists()) {      try {        Log.i("", settings+"+2+");        settings.createNewFile();        initSettings(settings);      } catch (IOException e) {        e.printStackTrace();        return;      }      return;    }        try {      = true);      = factory.newPullParser();      xpp.setInput(new FileInputStream(settings), "utf-8");      int eventType = xpp.getEventType();      while (eventType != "", eventType+"");        if (eventType == = xpp.getName();          Log.i("", "tag---------"+tag+"");          if (tag.equals("item")) {            String id = xpp.getAttributeValue(null, "id");            String value = xpp.getAttributeValue(null, "value");            if (id.equals("server")) {              sServerAddr = value;            } else if (id.equals("hotel")) {              sHid = value;            } else if (id.equals("room")) {              sRoomNum = value;            }          }        }        eventType = xpp.next();      }      Log.i("", eventType+"exist the xunhuan");    } catch (catch (FileNotFoundException e) {      e.printStackTrace();    } catch (IOException e) {      e.printStackTrace();    }  }

生成

//默认是没有换行的
public static void initSettings(final File settings) { new Thread(new Runnable() { @Override public void run() { FileOutputStream fos = null; try { fos = new FileOutputStream(settings); = "UTF-8"); serializer.startDocument("UTF-8", true); serializer.startTag(null, "config"); serializer.startTag(null, "category"); serializer.attribute(null, "name", "hot"); // server serializer.startTag(null, "item"); serializer.attribute(null, "id", "server"); serializer.attribute(null, "value", ""); serializer.endTag(null, "item"); // hid serializer.startTag(null, "item"); serializer.attribute(null, "id", "hotel"); serializer.attribute(null, "value", ""); serializer.endTag(null, "item"); // room serializer.startTag(null, "item"); serializer.attribute(null, "id", "room"); serializer.attribute(null, "value", ""); serializer.endTag(null, "item"); serializer.endTag(null, "category"); serializer.endTag(null, "config"); serializer.endDocument(); serializer.flush(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } } } }).start(); }