2016年10月25日 星期二

XmlSerializer、XmlPullParser (Android)

XmlSerializer:寫XML
XmlPullParser:讀XML

※Chess.java

public class Chess {
    private String chessName;
    private Integer price;
    
    // setter/getter...
}

※讀寫XML會用到的java bean


※XmlSerializer

public void btn(View view){
    List<Chess> chs = new ArrayList<>();
    String[] chessNames = {"象棋", "西洋棋", "五子棋"};
    Integer[] prices = {55, 60, 65};
    for (int i = 0; i < chessNames.length; i++) {
        Chess ch = new Chess();
        ch.setChessName(chessNames[i]);
        ch.setPrice(prices[i]);
        chs.add(ch);
    }
    
    System.out.println("寫檔");
    XmlSerializer xml = Xml.newSerializer();
    File f = new File(getApplicationContext().getFilesDir() + File.separator, "serializer.xml");
    try (OutputStream out = new FileOutputStream(f)){
        xml.setOutput(out, "UTF-8");
    
        xml.startDocument("UTF-8", true);
        xml.startTag(null, "map"); // null表示沒有namespace
        for (Chess chess : chs) {
            // chess node
            xml.startTag(null, "chess");
            xml.text(chess.getChessName());
            xml.endTag(null, "chess");
    
            // price node
            xml.startTag(null, "price");
            xml.text(chess.getPrice().toString());
            xml.endTag(null, "price");
        }
        xml.endTag(null, "map");
        xml.endDocument();
    } catch (FileNotFoundException e) {
            e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

※try有圓括號(java7)要在build.gradle(Module:app)這支檔案裡的
android->;defaultConfig->;minSdkVersion-->要在19(含)以上



※XmlPullParser

public void btn(View view){
    XmlPullParser xml = Xml.newPullParser();
    File f = new File(getApplicationContext().getFilesDir() + File.separator, "serializer.xml");
    try (InputStream in = new FileInputStream(f)){
        xml.setInput(in, "UTF-8");
    
        int type = xml.getEventType();
        while (type != XmlPullParser.END_DOCUMENT) {
            if(type == XmlPullParser.START_DOCUMENT) {
                System.out.println("Start document");
            } else if(type == XmlPullParser.START_TAG) {
                System.out.println("Start tag " + xml.getName());
            } else if(type == XmlPullParser.END_TAG) {
                System.out.println("End tag " + xml.getName());
            } else if(type == XmlPullParser.TEXT) {
                System.out.println("Text " + xml.getText());
            }
            type = xml.next();
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (XmlPullParserException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}



沒有留言:

張貼留言