简体   繁体   中英

How to parse custom user's tags?

There is the annotation @ElementMap , that allows to parse such tags to maps:

<field key="key">value</field>

Is it possible to parse such kinds of tags to maps?:

<key>value</key>

I tried to write custom converter for my class, but it still does not allow to use custom user's tags in xml.

I tried to write custom converter for my class, but it still does not allow to use custom user's tags in xml.

Can you give some more details?


Here's an example how you can implement the converter:

@Root
@Convert(Example.ExampleConverter.class)
public class Example
{
    private Map<String, String> map;

    // ...

    static class ExampleConverter implements Converter<Example>
    {
        @Override
        public Example read(InputNode node) throws Exception
        {
            Example value = new Example();
            value.map = new HashMap<>();

            InputNode childNode = node.getNext();

            while( childNode != null )
            {
                value.map.put(childNode.getName(), childNode.getValue());
                childNode = node.getNext();
            }

            return value;
        }

        @Override
        public void write(OutputNode node, Example value) throws Exception
        {
            for( Entry<String, String> entry : value.map.entrySet() )
            {
                node.getChild(entry.getKey()).setValue(entry.getValue());
            }
        }
    }
}

Example usage:

Serializer ser = new Persister(new AnnotationStrategy());

final String xml = "<example>\n"
        + "   <key1>value1</key1>\n"
        + "   <key2>value2</key2>\n"
        + "   <key3>value3</key3>\n"
        + "</example>";

Example e = ser.read(Example.class, xml);
System.out.println(e);

Output (depends on toString() -implementation:

Example{map={key1=value1, key2=value2, key3=value3}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM