如何防止样板 Java 代码解析复杂的 XML 文件?
我已经用 DocumentBuilderFactory 为复杂的 XML 文件编写了一个 XML 解析器。因为有许多不同的节点类型,所以有许多样板代码。对于每个节点类型(NodeName),我都有一个子节点循环和一个可能的子元素开关。
是否可以只为不同的节点类型注册所需的代码,然后运行解析?
I have written a XML parser with DocumentBuilderFactory for a complex XML file. Because there are many different node types that there are many boilerplate code. For every node type (NodeName) I have a loop over the children and a switch for the possible children elements.
Is it possible only to register the needed code for the different node types and then run the parsing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
几种方法:
Several ways:
Java DOM 解析 API 确实有点样板。还有一些其他库:
The Java DOM parsing API is indeed a bit boilerplate. There are some other libraries:
编写自定义解析器可能不是正确的方法。
如果您只需要将 XML 映射到 Java 对象,那么预先存在的库或工具是最好的。让其他人担心样板吧。
我是 Apache Digester 的忠实粉丝,它采用大量规则并为您构建 Java bean。如果需要更多的学习曲线,但需要更大的灵活性和功能,您可以使用 Apache XMLBeans。
Writing a custom parser may not be the way to go.
If you merely needs to map XML into Java objects, a preexisting library or tool is best. Let someone else worry about boilerplate.
I'm a big fan of Apache Digester, which takes a bunch of rules and buuilds the Java beans for you. For a little more of a learning curve but more flexibility and power you could use Apache XMLBeans.