Androidxml資料的讀取和寫入(sax,pull,dom,xstream,jsoup)

kandy_aliyq發表於2018-08-23

一、引用

1、用XmlSerializer寫xml檔案與讀xml檔案
2、xml解析(讀取xml,儲存檔案到xml)
3、Android-利用Document來對xml進行讀取和寫入操作
4、手把手教學 Android用jsoup解析html

文內相關其他XStream解析xml資料

1、Android XStream 解析xml資料變成bean,支援CDATA
2、Retrofit 用Soap協議訪問WebService 詳解

二、資料格式

1、xml資料

包含單個資料,列表資料,bean資料。有tag,attribute,content-text
以下我們就是我們要讀取和寫入的資料

 * <?xml version=`1.0` encoding=`utf-8` standalone=`yes` ?>
 * <xml_data>
 *      <user name="wujn" />
 *      <deviceinfos>
 *          <deviceinfo id="1">
 *               <name>儀器123</name>
 *               <price>188</price>
 *               <company>YYY</company>
 *               <usage>檢測獸藥殘留</usage>
 *          </deviceinfo>
 *          <deviceinfo id="2">
 *               <name>儀器456</name>
 *               <price>199</price>
 *               <company>XXX</company>
 *               <usage>檢測農藥殘留及多引數</usage>
 *          </deviceinfo>
 *      </deviceinfos>
 * </xml_data>

2、bean

public class DeviceInfo {
    String name;
    int id;
    int price;
    String company;
    String usage;

    public DeviceInfo(){}

    public DeviceInfo(String name,int id,int price,String company,String usage){
        this.name = name;
        this.id = id;
        this.price = price;
        this.company = company;
        this.usage = usage;
    }
     
   //省略get,set,tostring...
}  

三、寫入

1、XmlSerializer – xml序列,本質是pull

1.1、設定輸出檔案流FileOutputStream,xml序列號,文字格式…
1.2、startTag和endTag為一個元素的開始和結束標誌
1.3、attribute 是當前tag的屬性,一般來說bean的元素都可以放在裡面
1.4、text 是tag的content-text,就是文字值
1.5、關閉xml序列文字、關閉FileOutputStream

  /**寫入XML資料*/
    private void WriteXmlToSdcardByXmlSerial(){
        List<DeviceInfo> deviceInfoList = new ArrayList<>();
        DeviceInfo deviceInfo = new DeviceInfo("儀器123",1,188,"YYY","檢測獸藥殘留");
        DeviceInfo deviceInfo3 = new DeviceInfo("儀器456",2,199,"XXX","檢測農藥殘留及多引數");
        deviceInfoList.add(deviceInfo);
        deviceInfoList.add(deviceInfo3);

        try {
            //-------內部-----------
//            // 指定流目錄
//            OutputStream os = openFileOutput("persons.xml", Context.MODE_PRIVATE);
//            // 設定指定目錄
//            serializer.setOutput(os, "UTF-8");

            //--------外部---------
            //xml檔案的序列號器  幫助生成一個xml檔案
            FileOutputStream fos = new FileOutputStream(new File(xmlPath));

            //獲取到xml的序列號
            XmlSerializer serializer = Xml.newSerializer();
            //序列化初始化
            serializer.setOutput(fos, "utf-8");
            //建立xml
            serializer.startDocument("utf-8", true);

            //頂層element有且只有一個
            serializer.startTag(null,"xml_data");

            //tag+attribute:<user name="wujn" />
            //tag+text:<user>wujn</user>
            serializer.startTag(null,"user");
            serializer.attribute(null,"name","wujn");
            //serializer.text("wujn");
            serializer.endTag(null,"user");

            //多組<deviceinfo>...</deviceinfo>
            serializer.startTag(null,"deviceinfos");
            for(int i=0;i<deviceInfoList.size();i++){
                serializer.startTag(null,"deviceinfo");
                serializer.attribute(null,"id",String.valueOf(deviceInfoList.get(i).getId()));

                serializer.startTag(null,"name");
                serializer.text(deviceInfoList.get(i).getName());
                serializer.endTag(null,"name");

                serializer.startTag(null,"price");
                serializer.text(String.valueOf(deviceInfoList.get(i).getPrice()));
                serializer.endTag(null,"price");

                serializer.startTag(null,"company");
                serializer.text(deviceInfoList.get(i).getCompany());
                serializer.endTag(null,"company");

                serializer.startTag(null,"usage");
                serializer.text(deviceInfoList.get(i).getUsage());
                serializer.endTag(null,"usage");

                serializer.endTag(null,"deviceinfo");
            }
            serializer.endTag(null,"deviceinfos");

            //頂層element有且只有一個
            serializer.endTag(null,"xml_data");

            //關閉文件
            serializer.endDocument();
            //寫入流關閉
            fos.flush();
            fos.close();

            ToastUtil.showShort(instance,"xml資料已匯出");

        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            ToastUtil.showShort(instance,"xml資料匯出異常:"+e.getMessage());
        } catch (IllegalStateException e) {
            e.printStackTrace();
            ToastUtil.showShort(instance,"xml資料匯出異常:"+e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            ToastUtil.showShort(instance,"xml資料匯出異常:"+e.getMessage());
        }

    }

2、Document – dom形式

1.1、DocumentBuilderFactory工廠新建一個document
1.2、createElement 新建元素,裡面放的是tag值
1.3、setAttribute 設定attribute,一般bean類資料可放這裡
1.4、setTextContent 是tag的content-text,就是文字值
1.5、appendChild 新增節點元素,一層層自己控制
1.6、Transformer 把document轉成String
1.7、FileOutputStream 開啟,寫入String.getBytes(),關閉流

/**寫入XML資料*/
    private void WriteXmlToSdcardByDom(){
        List<DeviceInfo> deviceInfoList = new ArrayList<>();
        DeviceInfo deviceInfo = new DeviceInfo("儀器123",1,188,"YYY","檢測獸藥殘留");
        DeviceInfo deviceInfo3 = new DeviceInfo("儀器456",2,199,"XXX","檢測農藥殘留及多引數");
        deviceInfoList.add(deviceInfo);
        deviceInfoList.add(deviceInfo3);

        try {
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = null;
            documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document document = documentBuilder.newDocument();
            document.setXmlStandalone(true);
            document.setXmlVersion("1.0");

            //根節點
            Element root = document.createElement("xml_data");
            //user節點
            Element userE = document.createElement("user");
            userE.setAttribute("name","wujn");
            root.appendChild(userE);
            //deviceinfos節點
            Element devsE = document.createElement("deviceinfos");
            for(int i=0;i<deviceInfoList.size();i++){
                //單個deviceinfo節點
                Element devE = document.createElement("deviceinfo");
                devE.setAttribute("id",String.valueOf(deviceInfoList.get(i).getId()));

                Element nameE = document.createElement("name");
                nameE.setTextContent(deviceInfoList.get(i).getName());
                devE.appendChild(nameE);

                Element priceE = document.createElement("price");
                priceE.setTextContent(String.valueOf(deviceInfoList.get(i).getPrice()));
                devE.appendChild(priceE);

                Element companyE = document.createElement("company");
                companyE.setTextContent(deviceInfoList.get(i).getCompany());
                devE.appendChild(companyE);

                Element usageE = document.createElement("usage");
                usageE.setTextContent(deviceInfoList.get(i).getUsage());
                devE.appendChild(usageE);

                //新增deviceinfo節點
                devsE.appendChild(devE);
            }
            root.appendChild(devsE);
            document.appendChild(root);


            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();

            //轉成string
            transformer.setOutputProperty("encoding","utf-8");
            StringWriter stringWriter = new StringWriter();
            transformer.transform(new DOMSource(document),new StreamResult(stringWriter));
            LogUtil.i("xml stream = "+stringWriter.toString());

            //xml檔案的序列號器  幫助生成一個xml檔案
            FileOutputStream fos = new FileOutputStream(new File(xmlPath));
            fos.write(stringWriter.toString().getBytes());
            //寫入流關閉
            fos.flush();
            fos.close();

            ToastUtil.showShort(instance,"xml資料已匯出");

        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            ToastUtil.showShort(instance,"xml資料匯出異常:"+e.getMessage());
        } catch (IllegalStateException e) {
            e.printStackTrace();
            ToastUtil.showShort(instance,"xml資料匯出異常:"+e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            ToastUtil.showShort(instance,"xml資料匯出異常:"+e.getMessage());
        }catch (ParserConfigurationException e) {
            e.printStackTrace();
            ToastUtil.showShort(instance,"xml資料匯出異常:"+e.getMessage());
        }catch (TransformerConfigurationException e) {
            e.printStackTrace();
            ToastUtil.showShort(instance,"xml資料匯出異常:"+e.getMessage());
        }catch (TransformerException e) {
            e.printStackTrace();
            ToastUtil.showShort(instance,"xml資料匯出異常:"+e.getMessage());
        }

    }

四、讀取

1、XmlPullParser – Pull形式,一行行解析的,減少記憶體消耗

1、xml解析器設定解讀編碼和FileInputStream
2、getEventType 獲得tag標籤型別,按照不同型別進行解析
XmlResourceParser.END_DOCUMENT
XmlResourceParser.START_TAG
XmlResourceParser.TEXT – 標籤內文字content-text
XmlResourceParser.END_TAG
3、next() 下一行,還有nextTag,nextText等
5、資料整合
6、關閉FileInputStream流

注意://如果xml節點確定是文字,需要檢查XmlResourceParser.TEXT,防止getText() 返回 null。
/**
     * XmlPullParser - 讀取XML資料
     * 邏輯上有可能有不嚴謹的地方
     * */
    private void ReadXmlFromSdcardByPull(){
        File xmlFile = new File(xmlPath);
        if(xmlFile.exists()){

            try {
                StringBuilder sb = new StringBuilder();
                sb.append(" -- XmlPullParser --
");
                List<DeviceInfo> deviceInfoList = new ArrayList<>();
                DeviceInfo deviceInfo = null;
                boolean convertDeviceInfo = false;

                //檔案寫入流
                FileInputStream fis = new FileInputStream(xmlFile);
                //xml解析
                XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
                factory.setNamespaceAware(true);
                XmlPullParser xrp = factory.newPullParser();
                //設定input encode
                xrp.setInput(fis, "UTF-8");


                while (xrp.getEventType() != XmlResourceParser.END_DOCUMENT) {
                    if (xrp.getEventType() == XmlResourceParser.START_TAG) {
                        String tagName = xrp.getName();

                        if (tagName.equals("user")) {
                            String name = xrp.getAttributeValue(null, "name");
                            sb.append("user.name="+name+"
");
                        }

                        else if(tagName.equals("deviceinfos")){
                            //nothing to do
                        }

                        else if(tagName.equals("deviceinfo")){
                            deviceInfo = new DeviceInfo();
                            int id = Integer.parseInt(xrp.getAttributeValue(null, "id"));
                            deviceInfo.setId(id);
                            LogUtil.d("id="+id);
                            convertDeviceInfo = true;
                        }

                        //解析 DeviceInfo
                        //<StartTag>text<EndTag> 是三個元素
                        if(convertDeviceInfo){
                            if(tagName.equals("name")) {
                                xrp.next();
                                //必須檢查如果當前 xml 節點是文字,以便 getText() 不會返回 null。
                                if (xrp.getEventType() == XmlResourceParser.TEXT){
                                    String name = xrp.getText();
                                    deviceInfo.setName(name);
                                    LogUtil.d("name="+name);
                                }
                                xrp.next();

                            }

                            else if(tagName.equals("price")){
                                xrp.next();
                                if (xrp.getEventType() == XmlResourceParser.TEXT){
                                    int price = Integer.parseInt(xrp.getText());
                                    deviceInfo.setPrice(price);
                                    LogUtil.d("price="+price);
                                }
                                xrp.next();
                            }

                            else if(tagName.equals("company")){
                                xrp.next();
                                if (xrp.getEventType() == XmlResourceParser.TEXT){
                                    String company = xrp.getText();
                                    deviceInfo.setCompany(company);
                                    LogUtil.d("company="+company);
                                }
                                xrp.next();
                            }

                            else if(tagName.equals("usage")){
                                xrp.next();
                                if (xrp.getEventType() == XmlResourceParser.TEXT){
                                    String usage = xrp.getText();
                                    deviceInfo.setUsage(usage);
                                    LogUtil.d("usage="+usage);
                                }
                                xrp.next();
                            }
                        }

                    }

                    else if(xrp.getEventType() == XmlResourceParser.END_TAG){
                        String tagName = xrp.getName();
                        if(tagName.equals("deviceinfo")){
                            deviceInfoList.add(deviceInfo);
                            deviceInfo = null;
                            convertDeviceInfo = false;
                        }
                    }
                    //xrp.nextTag();
                    //xrp.nextText();
                    xrp.next();
                }

                //關閉流
                fis.close();
                fis=null;

                for (int i=0;i<deviceInfoList.size();i++){
                    sb.append(deviceInfoList.get(i).toString()+"
");
                }

                tv_result.setText(sb.toString());

            } catch (IllegalArgumentException e) {
                e.printStackTrace();
                ToastUtil.showShort(instance,"xml資料匯入異常:"+e.getMessage());
            } catch (IllegalStateException e) {
                e.printStackTrace();
                ToastUtil.showShort(instance,"xml資料匯入異常:"+e.getMessage());
            } catch (IOException e) {
                e.printStackTrace();
                ToastUtil.showShort(instance,"xml資料匯入異常:"+e.getMessage());
            } catch (XmlPullParserException e) {
                e.printStackTrace();
                ToastUtil.showShort(instance,"xml資料匯入異常:"+e.getMessage());
            }

        }else{
            ToastUtil.showShort(instance,"xml檔案不存在");
        }

    }

2、SAXParser – SAX形式

1、sax解析器設定FileInputStream 和解析助手handler
2、解析助手TestXmlHandler extends DefaultHandler
startDocument 開始文件
endDocument 結束文件
startElement 元素開始 :localName=tag標籤名,attribute元素.getValue()獲取元素值
endElement 元素結束
characters 元素內content-text
3、FileInputStream 劉關閉

注意:org.apache.harmony.xml.ExpatParser$ParseException: At line 1, column 76: junk after document element 這個異常是要麼解析器解析寫錯了,要麼就是xml文件不規範,比如頂層元素有多個,規定標準是隻有一個頂層元素,在這裡是xml_data
/**
     * SAXParser - 讀取XML資料
     * 邏輯上有可能有不嚴謹的地方
     *
     * org.apache.harmony.xml.ExpatParser$ParseException: At line 1, column 76: junk after document element
     * 頂層元素不止一個的異常
     * */
    private void ReadXmlFromSdcardBySAX(){
        File xmlFile = new File(xmlPath);
        if(xmlFile.exists()){
            try {
                final StringBuilder sb = new StringBuilder();
                sb.append(" -- SAXParser --
");

                //檔案寫入流
                FileInputStream fis = new FileInputStream(xmlFile);

                SAXParserFactory spf = SAXParserFactory.newInstance();
                SAXParser saxParser = spf.newSAXParser();//建立解析器
                //設定解析器的相關特性,http://xnl.org/sax/features/namespaces = true;
                //表示開啟名稱空間特性
                //saxParser.setProperty("http://xnl.org/sax/features/namespaces", true);
                TestXmlHandler handler = new TestXmlHandler() {
                    @Override
                    void onStart() {
                        LogUtil.i("SAXParser onStart >>> ");
                    }

                    @Override
                    void onEnd(String username, List<DeviceInfo> deviceInfoList) {
                        LogUtil.i("SAXParser onEnd >>> ");

                        sb.append("user.name="+username+"
");
                        for (int i=0;i<deviceInfoList.size();i++){
                            sb.append(deviceInfoList.get(i).toString()+"
");
                        }

                        tv_result.setText(sb.toString());
                    }
                };
                saxParser.parse(fis, handler);

//                InputSource inputSource = new InputSource();
//                inputSource.setEncoding("utf-8");
//                inputSource.setCharacterStream(new StringReader(xmlPath));
//                saxParser.parse(new InputSource(new FileReader(new File(xmlPath))), handler);

                //關閉流
                fis.close();
                fis=null;

            }catch (IOException e){
                e.printStackTrace();
                ToastUtil.showShort(instance,"xml資料匯入異常:"+e.getMessage());
            }catch (SAXException e){
                e.printStackTrace();
                ToastUtil.showShort(instance,"xml資料匯入異常:"+e.getMessage());
            }catch (ParserConfigurationException e){
                e.printStackTrace();
                ToastUtil.showShort(instance,"xml資料匯入異常:"+e.getMessage());
            }

        }else{
            ToastUtil.showShort(instance,"xml檔案不存在");
        }

    }


    /**
     * TestXmlHandler - SAX的解析器
     * 靠preTag也可以達到convertDeviceInfo類似的效果
     * */
    abstract class TestXmlHandler extends DefaultHandler{
        private String username = "";
        private List<DeviceInfo> deviceInfoList = new ArrayList<>();
        private DeviceInfo deviceInfo = null;
        private boolean convertDeviceInfo = true;

        private String preTag;//之前tag

        @Override
        public void startDocument() throws SAXException {
            onStart();
        }
        @Override
        public void endDocument() throws SAXException {
            onEnd(username, deviceInfoList);
        }
        abstract void onStart();
        abstract void onEnd(String username,List<DeviceInfo> deviceInfoList);

        @Override
        public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
            LogUtil.d("startElement: uri="+uri+", localName="+localName+", qName="+qName);
            preTag = localName;

            if("user".equals(localName)){
                username = attributes.getValue("name");
            }

            else if("deviceinfos".equals(localName)){
                //will be more deviceinfo
            }

            else if("deviceinfo".equals(localName)){
                deviceInfo = new DeviceInfo();
                int id = Integer.parseInt(attributes.getValue("id"));
                deviceInfo.setId(id);
                convertDeviceInfo = true;
            }
        }

        @Override
        public void endElement(String uri, String localName, String qName) throws SAXException {
            LogUtil.d("endElement: uri="+uri+", localName="+localName+", qName="+qName);
            preTag = null;

            if("deviceinfo".equals(localName)){
                deviceInfoList.add(deviceInfo);
                deviceInfo = null;
                convertDeviceInfo = false;
            }
        }

        @Override
        public void characters(char[] ch, int start, int length) throws SAXException {
            String data = new String(ch,start,length);
            LogUtil.d("characters: preTag="+preTag+", data="+data);

            if(convertDeviceInfo){
                if(preTag.equals("name")) {
                    deviceInfo.setName(data);
                    LogUtil.d("name="+data);
                }

                else if(preTag.equals("price")){
                    int price = Integer.parseInt(data);
                    deviceInfo.setPrice(price);
                    LogUtil.d("price="+price);
                }

                else if(preTag.equals("company")){
                    deviceInfo.setCompany(data);
                    LogUtil.d("company="+data);
                }

                else if(preTag.equals("usage")){
                    deviceInfo.setUsage(data);
                    LogUtil.d("usage="+data);
                }
            }
        }


    }

3、Document – dom形式:此方式需要讀取整個流資料,佔用記憶體較大,一般針對小型xml資料可以用此方法,有點在於簡單易懂

1、document載入輸入流
2、getElementsByTagName 獲得該tag名下的所有節點
3、每個node(Element)都有獲取屬性,屬性name和值.getAttributes().getNamedItem(“name”).getNodeValue()
4、每個node(Element)的文字值 content-text : getTextContent();
5、關閉輸入流

/**
     * Document - 讀取XML資料
     * 直觀明瞭,但是要預載入所有資料,對xml比較大佔記憶體比較多
     * */
    private void ReadXmlFromSdcardByDom(){
        File xmlFile = new File(xmlPath);
        if(xmlFile.exists()){
            try {
                StringBuilder sb = new StringBuilder();
                sb.append(" -- Document --
");

                DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder documentBuilder = null;
                documentBuilder = documentBuilderFactory.newDocumentBuilder();

                //載入輸入流到document中
                //InputStream inputStream = getAssets().open("person.xml");
                FileInputStream fis = new FileInputStream(xmlFile);
                Document document = documentBuilder.parse(fis);

                NodeList userNodes = document.getElementsByTagName("user");
                for(int i=0;i<userNodes.getLength();i++){
                    sb.append("user.name="+userNodes.item(i).getAttributes().getNamedItem("name").getNodeValue()+"
");
                }

                List<DeviceInfo> deviceInfoList = new ArrayList<>();
                DeviceInfo deviceInfo = null;
                NodeList deviceNodes = document.getElementsByTagName("deviceinfo");
                //裝置節點
                for(int i=0;i<deviceNodes.getLength();i++){
                    deviceInfo = new DeviceInfo();
                    Node deviceNode = deviceNodes.item(i);
                    int id = Integer.parseInt(deviceNode.getAttributes().getNamedItem("id").getNodeValue());
                    LogUtil.d("id="+id);
                    deviceInfo.setId(id);

                    NodeList eachDeviceNodes = deviceNode.getChildNodes();
                    LogUtil.d("eachDeviceNodes.length="+eachDeviceNodes.getLength());
                    //裝置下值節點
                    for(int j=0;j<eachDeviceNodes.getLength();j++){
                        String tagName = eachDeviceNodes.item(j).getNodeName();//nodename not localname
                        LogUtil.d("tagName=" + tagName);
                        String data = eachDeviceNodes.item(j).getTextContent();

                        if (tagName.equals("name")) {
                            deviceInfo.setName(data);
                            LogUtil.d("name=" + data);
                        } else if (tagName.equals("price")) {
                            int price = Integer.parseInt(data);
                            deviceInfo.setPrice(price);
                            LogUtil.d("price=" + price);
                        } else if (tagName.equals("company")) {
                            deviceInfo.setCompany(data);
                            LogUtil.d("company=" + data);
                        } else if (tagName.equals("usage")) {
                            deviceInfo.setUsage(data);
                            LogUtil.d("usage=" + data);
                        }

                    }
                    //新增裝置到列表
                    deviceInfoList.add(deviceInfo);
                }

                //關閉流
                fis.close();
                fis=null;

                for (int i=0;i<deviceInfoList.size();i++){
                    sb.append(deviceInfoList.get(i).toString()+"
");
                }

                tv_result.setText(sb.toString());

            }catch (IOException e){
                e.printStackTrace();
                ToastUtil.showShort(instance,"xml資料匯入異常:"+e.getMessage());
            }catch (ParserConfigurationException e){
                e.printStackTrace();
                ToastUtil.showShort(instance,"xml資料匯入異常:"+e.getMessage());
            }catch (SAXException e){
                e.printStackTrace();
                ToastUtil.showShort(instance,"xml資料匯入異常:"+e.getMessage());
            }
        }else{
            ToastUtil.showShort(instance,"xml檔案不存在");
        }
    }

4、Jsoup- 和上面dom類似

1、Jsoup.parse 、Jsoup.connect 載入url或者htmlstring或者檔案
2、getElementsByTag 獲得該tag名下的所有節點,
3、children() 獲得某節點元素下的所有元素
4、每個Element都有獲取屬性,attr(key)
5、每個Element的文字值 content-text : text();

compile `org.jsoup:jsoup:1.9.2`
/**
     * Jsoup - 讀取XML資料(本質是document)
     * 直觀明瞭,但是要預載入所有資料,對xml比較大佔記憶體比較多
     * */
    private void ReadXmlFromSdcardByJsoup(){
        File xmlFile = new File(xmlPath);
        if(xmlFile.exists()){
            try {
                StringBuilder sb = new StringBuilder();
                sb.append(" -- Jsoup --
");

                //url網址作為輸入源
                //Document doc = Jsoup.connect("http://www.example.com").timeout(60000).get();

                //File檔案作為輸入源
                //File input = new File("/tmp/input.html");
                //Document doc = Jsoup.parse(input, "UTF-8", "http://www.example.com/");

                org.jsoup.nodes.Document document = Jsoup.parse(xmlFile, "UTF-8");
                org.jsoup.select.Elements userE = document.getElementsByTag("user");
                for(int i=0;i<userE.size();i++){
                    sb.append("user.name="+userE.get(i).attr("name")+"
");
                }


                List<DeviceInfo> deviceInfoList = new ArrayList<>();
                DeviceInfo deviceInfo = null;
                org.jsoup.select.Elements deviceE = document.getElementsByTag("deviceinfo");
                //裝置節點
                for(int i=0;i<deviceE.size();i++){
                    deviceInfo = new DeviceInfo();
                    org.jsoup.nodes.Element devE = deviceE.get(i);
                    int id = Integer.parseInt(devE.attr("id"));
                    LogUtil.d("id="+id);
                    deviceInfo.setId(id);

                    org.jsoup.select.Elements eachDeviceElements = devE.children();
                    LogUtil.d("eachDeviceElements.length="+eachDeviceElements.size());
                    //裝置下值節點
                    for(int j=0;j<eachDeviceElements.size();j++){
                        String tagName = eachDeviceElements.get(j).tagName();
                        String data = eachDeviceElements.get(j).text();
                        LogUtil.d("tagName=" + tagName + ", text="+data);

                        if (tagName.equals("name")) {
                            deviceInfo.setName(data);
                        } else if (tagName.equals("price")) {
                            int price = Integer.parseInt(data);
                            deviceInfo.setPrice(price);
                        } else if (tagName.equals("company")) {
                            deviceInfo.setCompany(data);
                        } else if (tagName.equals("usage")) {
                            deviceInfo.setUsage(data);
                        }

                    }

                    //新增裝置到列表
                    deviceInfoList.add(deviceInfo);
                }

                //關閉流
                //fis.close();
                //fis=null;

                for (int i=0;i<deviceInfoList.size();i++){
                    sb.append(deviceInfoList.get(i).toString()+"
");
                }

                tv_result.setText(sb.toString());



            }catch (IOException e){
                e.printStackTrace();
                ToastUtil.showShort(instance,"xml資料匯入異常:"+e.getMessage());
            }
        }else{
            ToastUtil.showShort(instance,"xml檔案不存在");
        }
    }

五、讀取和寫入文字

/**
     * 從file檔案中讀取string來
     * */
    public static String readFromFile(String fPath) throws IOException{
        BufferedReader bf = new BufferedReader(new FileReader(fPath));

        String content = "";
        StringBuilder sb = new StringBuilder();

        while (content != null) {
            content = bf.readLine();
            if (content == null) {
                break;
            }
            sb.append(content.trim());
        }
        bf.close();

        return sb.toString();
    }

    /**
     * 寫string到file檔案中
     * */
    public static void writeToFile(String content,String fPath)throws IOException{
        File txt = new File(fPath);
        if (!txt.exists()) {
            txt.createNewFile();
        }

        FileOutputStream fos = new FileOutputStream(txt);
        fos.write(content.getBytes());
        fos.flush();
        fos.close();
    }


相關文章