Search code examples
javaxmlobjectmapper

How to deserialize XML with key value pairs with XMLMapper


I have a very simple XML file but I can't seem to get it to deserialize back into a POJO.

The file looks like:

<?xml version="1.0"?>
<Settings>
    <property name="a"  value="1"/>
    <property name="b"  value="2"/>
    <property name="c"  value="3"/>
    [...]       
</Settings>

With a very simple method of

  public void convertXml() {

    try {
      final XmlMapper xmlMapper = new XmlMapper();
      final Configuration configuration = xmlMapper.readValue(rawXml.getFile(), Configuration.class);

      log.info("Configuration parsed {}", configuration);

    } catch (final IOException e) {
      e.printStackTrace();
    }
  }

And a couple of classes of which I'd have thought it would have gone into

public class Configuration {    
  private Settings settings;
}


public class Settings {
  private List<Property> property;
}


public class Property {
  private String name;

  private String value;
}

However the Configuration object just has a null value for the Settings property.

Have I missed the obvious here?


Solution

  • A couple of annotations was the answer in the end

    @JacksonXmlRootElement(localName = "Settings")
    public class Configuration {
    
      @JacksonXmlElementWrapper(useWrapping = false)
      private List<Property> property;
    }
    

    And this allowed me to drop the middle Settings class.