使用SIMPLE XML库为Android解析不同命名的元素作为单个列表

我想知道是否有使用SIMPLE XML Library for Android将col_1,col_2等作为列表而不是单独的元素处理。 我一直在阅读有关替换的内容,但我仍然感到困惑。

目前的格式:

 table  

我希望能够将col作为某种列表解析出来,这样我就可以处理任意数量的cols。 这可能吗?

正如ng之前所说:使用Converter 。 简单就是让您自定义处理的每一步(另一方面,它可以让您(甚至)使用某些代码行(甚至是复杂的结构)来序列化。

所以这是一个例子:

一个将保存列表中的值的类:

 @Root(name = "example") @Convert(value = ListConverter.class) // Specify the Converter that's used for this class public class Example { // This element will be set with the values from 'box-headers' element @ElementList(name = "box-headers") private List values; // This constructor is used to set the values while de-serializing // You can also use setters instead Example(List values) { this.values = values; } //... } 

Converter

 public class ExampleConverter implements Converter { @Override public Example read(InputNode node) throws Exception { List list = new ArrayList<>(); // List to insert the 'col_' values NodeMap attributes = node.getAttributes(); // All attributes of the node Iterator itr = attributes.iterator(); while( itr.hasNext() ) // Iterate over all attributes { final String name = itr.next(); // The name of the attribute if( name.startsWith("col_") ) // Check if it is a 'col' attribute { // Insert the value of the 'col_' attribute list.add(attributes.get(name).getValue()); } } // Return the result - instead of a constructor you can use setter(s) too return new Example(list); } @Override public void write(OutputNode node, Example value) throws Exception { // TODO: Implement serializing here - only required if you want to serialize too } } 

如何使用:

 // Serializer, don't forget `AnnotationStrategy` - without it wont work Serializer ser = new Persister(new AnnotationStrategy()); // Deserialize the object - here the XML is readen from a file, other sources are possible Example ex = ser.read(Example.class, new File("test.xml")); 

此示例仅使用col_xy属性,其他所有内容都将被删除。 如果您也需要这些值,则很容易实现它们。 您只需从InputNode检索它们并将它们设置到输出中。