Parsing differently named elements as a single list using SIMPLE XML library for android

喜欢而已 提交于 2019-12-08 22:01:36

As ng said before: Use a Converter for this. Simple is brilliant in letting you customize every step of processing (while on the other hand it's possible to let you (de-)serialize even complex structures with some lines of code).

So here's an example:

A Class that will hold the values from the list:

@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<String> values;


    // This constructor is used to set the values while de-serializing
    // You can also use setters instead
    Example(List<String> values)
    {
        this.values = values;
    }

    //...
}

The Converter:

public class ExampleConverter implements Converter<Example>
{
    @Override
    public Example read(InputNode node) throws Exception
    {
        List<String> list = new ArrayList<>(); // List to insert the 'col_' values

        NodeMap<InputNode> attributes = node.getAttributes(); // All attributes of the node
        Iterator<String> 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
    }
}

How to use:

// 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")); 

This example uses only col_xy attributes, everything else is dropped. If you need those values too it's easy to implement them. You only have to retrieve them from the InputNode and set them into your output.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!