SimpleXML 解析忽略@Root 名称参数

SimpleXML parse ignores @Root name parameter

SimpleXML 库有问题。它忽略 @Root 名称。这是带有测试的代码:

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
    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);

    }

无论 xml 中的第一个标记是什么,测试都会通过,即“

........
@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);
}

您可以使用@Converter 注释覆盖读取方法,并通过获取注释值来验证根名称。