How to append tags in XML in Android?

前端 未结 4 1296
抹茶落季
抹茶落季 2020-12-29 16:12

I would like to write some content to a XML file. For that I have created a XML file and writen tags with element, attribute and value with some data like this:



        
4条回答
  •  囚心锁ツ
    2020-12-29 16:29

    I don't really see your point but for myself i've used this example and it worked just fine

    private String writeXml(List messages){
        XmlSerializer serializer = Xml.newSerializer();
        StringWriter writer = new StringWriter();
        try {
            serializer.setOutput(writer);
            serializer.startDocument("UTF-8", true);
            serializer.startTag("", "messages");
            serializer.attribute("", "number", String.valueOf(messages.size()));
            for (Message msg: messages){
                serializer.startTag("", "message");
                serializer.attribute("", "date", msg.getDate());
                serializer.startTag("", "title");
                serializer.text(msg.getTitle());
                serializer.endTag("", "title");
                serializer.startTag("", "url");
                serializer.text(msg.getLink().toExternalForm());
                serializer.endTag("", "url");
                serializer.startTag("", "body");
                serializer.text(msg.getDescription());
                serializer.endTag("", "body");
                serializer.endTag("", "message");
            }
            serializer.endTag("", "messages");
            serializer.endDocument();
            return writer.toString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } 
    }
    

    You can read the full article here

提交回复
热议问题