简单框架 - 未知的xml标签解析

时间:2016-05-03 09:54:12

标签: java android xml simple-framework

我正在开发基于Simple Framework的android项目。有一段时间我注意到我必须实现动态解析。简而言之,我有一个从后端下载的大型xml文件。这个xml文件可以包含不时变化的标签和我的应用程序使用的不可更改的标签。

我们说我有这个xml文件:

<note>
  <to>Tove</to>
  <from>Jani</from>
  <heading>Reminder</heading>
  <body>Don't forget me this weekend!</body>
  <age>33</age>
</note>

和java模型类

@Root(name="note", strict = false)    
public class Note {
    @Element(name = "to", required = false)
    public String to;
    @Element(name = "from", required = false)
    public String from;
    @Element(name = "heading", required = false)
    public String heading;
    @Element(name = "body", required = false)
    public String body;
    @Element(name = "age", required = false)
    public int age;

    //getters/setters...   
}

但有时我可以下载看起来像这样的xml(x1 - 未知名称):

<note>
  <x1>content...</x1>
  <to>Tove</to>
  <from>Jani</from>
  <heading>Reminder</heading>
  <x2>content...</x2>
  <body>Don't forget me this weekend!</body>
  <age>33</age>
  <x3>content...</x3>
  <xN>content...</xN>
</note>

在这种情况下,当我的应用程序读取/编辑此xml并保存到xml文件以发送回后端时,没有 x1..xN 标记,因为我不知道如何维护他们在我的模特中。

我的应用程序基于包含pojo类的大模型层,因此我需要找到一个存储此未知标记的解决方案。

1 个答案:

答案 0 :(得分:1)

您可以尝试创建自定义NoteConverter。

public class NoteConverter implements Converter<Note> {

    public Note read(InputNode node) {
        // manually read all nodes
        // assign values to members: to, from, heading, body, age
        // other values save in some structure ex. Map inside the Note element

        return note;
   }

   public void write(OutputNode node, Note note) {
        // manually write note into outputNode
        // first write members: to, from, heading, body, age
        // finally write other nodes stored in map created in read function
   }

}

使用@Convert注释注释(NoteConverter.class)
AnnotationStrategy 添加到序列化程序