java中基于xml的自动类模型创建
我有一个 xml 文件格式,并使用该 xml 我想创建序列化和反序列化该 xml 所需的骨架类。我为此使用 Java 和 XStream。
.net 世界中有一个工具可以使用 xml 创建类。 Java世界里有类似的东西吗?
I have an xml file format and using that xml I want to create skeleton classes needed to serialize and de-serialize that xml. I am using Java and XStream for this.
There is tool in .net world which creates classes using xml. Is there anything similar in Java world?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我自己没有使用过 XStream,所以这个解决方案可能并不 100% 适合你。然而,Java 中最简单的方法是使用 Java 的 Architectural Binding for XML (JAXB) API 和工具。随着 Java 6 的发布,JAXB 被包含在 JDK 中。要从 XML 模式生成 Java 代码,您可以使用 xjc JDK自带的命令。下面是一个示例:
此代码生成方法将创建包含 JAXB 特定注释的 Java 对象,Marshaller 使用这些注释将 Java 对象映射到其 XML 格式,反之亦然。它还将包含许多警告,指出代码是自动生成的,不应修改。只要您不尝试自动使代码与 XML 保持同步,您就可以忽略这些消息。
现在,正如我所提到的,该技术确实会生成 JAXB 带注释的类,但是,生成的代码可能仍然与 XStream 兼容,因为我相信 XStream 使用简单的属性名称 -> xml节点名称转换逻辑。
I have not used XStream myself, so this solution may not 100% work for you. However, the simplest approach in Java is to use Java's Architectural Binding for XML (JAXB) API and tools. JAXB was included as part of the JDK with the release of Java 6. To generate Java code from an XML schema you would use the xjc command that comes with the JDK. Here is an example:
This code generation method will create Java Objects that include JAXB-specific annotations that are used by the Marshaller to map the Java object to its XML format and vice versa. It will also contain number of warnings stating that the code was auto-generated and should not be modified. As long as you are not trying to automatically keep the code in synch with your XML you could ignore these messages.
Now, as I mentioned, this technique does generate JAXB annotated classes, however, the generated code may still be compatible with XStream as I believe XStream uses simple attribute name -> xml node name conversion logic.