Sourceforge SimpleXML batch processing

SimpleXML can serialize a Java Enum view, but when it comes to de-serializing, it returns null instead of creating Enum from the generated XML. Is something that I am doing wrong, Enum serialization not supported at all?

Serialization returns this:

<TestStatus>
  <status>Functional</status>
</TestStatus>

Test Enum:

   @Root
    public enum TestStatus {

        AVAILABLE("Functional"),
        NOT_AVAILABLE("Dysfunctional");

        @Element
        private String status;

        private Status(String status) {
            this.status = status;
        }

        public String getStatus() {
            return status;
        }
    }
+3
source share
2 answers

How do you serialize your listing?

if you use it like this, it should work without problems, but will return several different XML:

Example:

@Root
public class Example
{
    @Element
    private TestStatus status = TestStatus.AVAILABLE;

    // ...
}

Test:

final File f = new File("test.xml");

Serializer ser = new Persister();
ser.write(new Example(), f);

Example m = ser.read(Example.class, f);

XML:

<example>
   <status>AVAILABLE</status>
</example>

You can rename xml tags using annotation pointers, but this value will not be changed.


Another (possible) solution uses a custom converter:

List annotations:

@Root()
@Convert(TestStatusConverter.class)
public enum TestStatus
{
    // ...
}

()

public class TestStatusConverter implements Converter<TestStatus>
{
    @Override
    public TestStatus read(InputNode node) throws Exception
    {
        final String value = node.getNext("status").getValue();

        // Decide what enum it is by its value
        for( TestStatus ts : TestStatus.values() )
        {
            if( ts.getStatus().equalsIgnoreCase(value) )
                return ts;
        }
        throw new IllegalArgumentException("No enum available for " + value);
    }


    @Override
    public void write(OutputNode node, TestStatus value) throws Exception
    {
        // You can customize your xml here (example structure like your xml)
        OutputNode child = node.getChild("status");
        child.setValue(value.getStatus());
    }
}

():

final File f = new File("test.xml");

// Note the new Strategy
Serializer ser = new Persister(new AnnotationStrategy());

ser.write(TestStatus.AVAILABLE, f);
TestStatus ts = ser.read(TestStatus.class, f);

System.out.println(ts);

( ):

, AnnotationStrategy

+2

, .

-2

Source: https://habr.com/ru/post/1792245/


All Articles