简体   繁体   English

在Java中按模板解析文档

[英]Parse document by template in Java

Is there any ready-to-use java library that, given a template, can read an xml-file that complies with that template and parse its values into a Java class? 是否有任何现成的java库,给定一个模板,可以读取符合该模板的xml文件并将其值解析为Java类? Sort of the job velocity does but in the reverse direction. 作业速度的排序确实如此,但方向相反。

For example, given the following template 例如,给出以下模板

<person>
  <name>${person.name}</name>
  <age>${person.age}</age>
</person>

and the input file 和输入文件

<person>
  <name>John</name>
  <age>20</age>
</person>

it could read its values into class 它可以将其价值读入课堂

class Person {
    public String name;
    public Integer age;
}

UPDATE: The example above is meant to show the general idea and has nothing to do with the serialization. 更新:以上示例旨在显示一般概念,与序列化无关。 Real example can also have elements and attributes that correspond to the fields related to the different Java object and the input file can have structure which cannot be used to deserialize objects with the values located across different attributes of different XML elements. 真实示例还可以具有与不同Java对象相关的字段对应的元素和属性,并且输入文件可以具有不能用于使用位于不同XML元素的不同属性上的值来反序列化对象的结构。 So it's not a serialization issue. 所以这不是序列化问题。

You might want to look at Apache Digester as well : http://commons.apache.org/proper/commons-digester/guide/core.html - this doesn't use a template-approach , but it looks quite well suited for the problem stated here. 您可能也想查看Apache Digester: http//commons.apache.org/proper/commons-digester/guide/core.html - 这不使用模板方法,但它看起来非常适合这里说的问题。

( Originally a comment: but OP stated that this provided a viable solution for them - so moving to answer ) (原来是评论:但是OP表示这为他们提供了一个可行的解决方案 - 所以转而回答)

Another good XML serializer / deserializer is Simple : 另一个好的XML序列化器/解串器是Simple

File source = new File("person.xml");
Person person = serializer.read(Person.class, source);

Are you sure you need templates? 您确定需要模板吗? Maybe just serialization from XML to Object is enough for you, then you can try XStream http://x-stream.github.io/tutorial.html 也许只是从XML到Object的序列化就足够了,那么你可以试试XStream http://x-stream.github.io/tutorial.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM