How to parse and create java pojo for below xml in an efficient way? Kindly suggest any efficient parser.
XML format is
Serialization and Deserialization can be handle by JacksonXmlModule.
// Item.class - use lombok or create g/setters
@JsonPropertyOrder({"name", "description", "note"})
public class Item {
private String name;
private String description;
private String note;
}
// Test.class
package hello.service;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.xml.JacksonXmlModule;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import hello.entity.Item;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.*;
public class NameServiceImplTest {
ObjectMapper objectMapper;
@Before
public void setup() {
JacksonXmlModule xmlModule = new JacksonXmlModule();
xmlModule.setDefaultUseWrapper(false);
this.objectMapper = new XmlMapper(xmlModule);
this.objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
}
@Test
public void serializeTest() {
// Wrapper
@JacksonXmlRootElement(localName = "names")
class Names {
public List- item = new ArrayList<>();
}
Item item = new Item();
item.setName("Vladimir");
item.setDescription("Desc");
item.setNote("Note");
Item item2 = new Item();
item2.setName("Iva");
item2.setDescription("Desc2");
item2.setNote("Note2");
Names names = new Names();
names.item.add(item);
names.item.add(item2);
try {
String xml = objectMapper.writeValueAsString(names);
assertNotNull(xml);
System.out.println(xml);
} catch (Exception e) { // IOException
System.out.println(e.getMessage());
fail();
}
}
@Test
public void deserializeTest() {
String xml = "
" +
"name desc note " +
"name desc note " +
" ";
try {
List- names = objectMapper.readValue(xml, new TypeReference
>() {});
names.forEach(item -> {
assertEquals("name", item.getName());
assertEquals("desc", item.getDescription());
assertEquals("note", item.getNote());
} );
} catch (Exception e) { // IOException
}
}
}