lampenlampen
lampenlampen

Reputation: 947

simple-xml null to nil

I'm using the simple-xml framework (http://simple.sourceforge.net/home.php) for serializing objects.

Is there a built-in function or option, so that null will be converted to nil="true":

XML:

<example xsi:nil="true"/>

with xmlns:xsi="http://www.w3.org/2001/XML-Schema-instance"

Thanks

Upvotes: 2

Views: 974

Answers (2)

ninehundreds
ninehundreds

Reputation: 1105

As a note to Ollo's answer, if you are wanting to have the value set with the normal open and closing tags, you can use node.setValue on the else as shown below:

public class SoapNilConverter implements Converter<String> {

@Override
public String read(InputNode node) throws Exception {
    return null;
}

@Override
public void write(OutputNode node, String value) throws Exception {
    if (value == null || value.isEmpty()) {
        node.setAttribute("xsi:nil", "true");
        node.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
    } else {
        node.setValue(value);
    }
}

}

Upvotes: 0

ollo
ollo

Reputation: 25370

Not directly, but you can add this behaviour by implementing a custom Converter. This allows both directions, Serialization and Deserialization.

Just don't forget the AnnotationStrategy (shown in the link above).


Update

@Element(name = "example")
@Convert(ExampleConverter.class)
private String example = "";

// ...

static class ExampleConverter implements Converter<String>
{
    // ...

    @Override
    public void write(OutputNode node, String value) throws Exception
    {
        if( value == null || value.isEmpty() == true )
        {
            node.setAttribute("xsi:nil", "true");
        }
        else
        {
            node.setAttribute("xsi:nil", value);
        }
    }
}

This will produce following XML if an empty value is set:

<SomeClass>
   <example xsi:nil="true"/>
</SomeClass>

Otherwise the actual value is used.

Upvotes: 2

Related Questions