SimpleXML library has issue. It ignores @Root name. Here is code with test:
Class:
@Root(name = "res", strict = true)
@Data
@NoArgsConstructor
@AllArgsConstructor
class Response {
@Attribute(name = "a")
private Integer a;
@Attribute(name = "i")
private Integer i;
@Attribute(name = "o", required = false)
private Integer o;
}
Test:
@Test
public void detectXml() {
Serializer serializer = new Persister();
String xml = "<xxx a=\"1\" i=\"1\"/>";
Response res = null;
try {
res = serializer.read(Response.class, xml);
} catch (Exception e) {
e.printStackTrace();
}
assertNotNull(res);
}
Test passes no matter what is first tag in xml ie."<xxx" library ignores @Root name "res". Any suggestions beside to switch to another XML parser library? Can anyone suggest one with class annotations like SimpleXML?
........
@Convert(Response.ResponseConverter.class)
class Response {
...........
public static class ResponseConverter implements Converter<Response> {
public ResponseTest read(InputNode node) throws Exception {
String rootAnnotation = ResponseTest.class.getAnnotation(Root.class).name();
if (!node.getName().equals(rootAnnotation) && node.isRoot()) {
return null;
}
return new ResponseTest();
}
.................
}
}
@Test
public void detectXml() {
Serializer serializer = new Persister();
String xml = "<xxx a=\"1\" i=\"1\"/>";
ResponseTest res = null;
try {
StringReader stringReader = new StringReader(xml);
res = new Persister(new AnnotationStrategy()).read(ResponseTest.class, NodeBuilder.read(stringReader));
if (res != null) {
res = serializer.read(ResponseTest.class, xml);
}
System.out.println(res);
} catch (Exception e) {
e.printStackTrace();
}
Assert.assertNotNull(res);
}
You can override the read method using @Converter annotation and validate the root name by fetching the Annotation value.