溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

利用Pull解析器生成XMl文件

發(fā)布時(shí)間:2020-07-21 18:58:07 來源:網(wǎng)絡(luò) 閱讀:624 作者:ghcomeon 欄目:開發(fā)技術(shù)

在Pull解析器解析XML文件(以下簡(jiǎn)稱上文)中是得到XMl文件中的數(shù)據(jù),那么該如何將應(yīng)用中的數(shù)據(jù)生成XMl文件呢?

 1.  在上文中的業(yè)務(wù)類PersonService中新建save()類,代碼如下


public static void save(List<Person> persons,OutputStream out) throws Exception{
        XmlSerializer serializer = Xml.newSerializer();//得到序列化器
        serializer.setOutput(out, "UTF-8");//輸出流對(duì)象
        //1.輸出<?xml version="1.0" encoding="UTF-8"?>,開始文檔
        serializer.startDocument("UTF-8", true);
        serializer.startTag(null, "persons");
        for (Person person : persons) {
            //生成<person ></person>
            serializer.startTag(null, "person");//開始節(jié)點(diǎn)
            serializer.attribute(null, "id", person.getId().toString());//生成id="10"
                                                                
            serializer.startTag(null, "name");
            serializer.text(person.getName());
            serializer.endTag(null, "name");  
                                                                
            serializer.startTag(null, "age");
            serializer.text(person.getAge().toString());
            serializer.endTag(null, "age");
                                                                        
            serializer.endTag(null, "person");//結(jié)束節(jié)點(diǎn)
        }
                                                                    
        serializer.endTag(null, "persons");
        serializer.endDocument();//文檔結(jié)束
        out.flush();//刷出數(shù)據(jù)
        out.close();//關(guān)閉輸出流
    }

2.在上文中Person類添加如下構(gòu)造方法


public Person(Integer id, String name, Integer age) {
        this.id = id;
        this.name = name;
        this.age = age;
    } 
    public Person(){}

3.在上文中PersonServiceTest類中添加如下測(cè)試方法


public void testSave() throws Exception{
        List<Person> persons = new ArrayList<Person>();
        persons.add(new Person(1,"gaoxxx",20));//為添加方便,為Person添加一個(gè)構(gòu)造器
        persons.add(new Person(2,"zhuxxx",21));
        persons.add(new Person(3,"linxxx",22));
        //<包>/files
        File xmlFile = new File(getContext().getFilesDir(),"AppToXml.xml");
        FileOutputStream outputStream = new FileOutputStream(xmlFile);//輸出流對(duì)象
        PersonService.save(persons, outputStream);
    }

   執(zhí)行該測(cè)試方法,就會(huì)在當(dāng)前應(yīng)用的包底下生成對(duì)應(yīng)的文件,復(fù)制到項(xiàng)目中,并利用Source—>Format進(jìn)行格式化,結(jié)果如下

利用Pull解析器生成XMl文件

在瀏覽器中打開的效果如下


利用Pull解析器生成XMl文件


向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI