简体   繁体   English

使用 java 从 .xsd 创建 .xml 文件

[英]creating a .xml file from .xsd with java

I'm a quite new to java world and I have a requirement of generating an .xml file from an .xsd file我是 Java 世界的新手,我需要从 .xsd 文件生成 .xml 文件

I did some research and found that 'jaxb' could do it.我做了一些研究,发现 'jaxb' 可以做到。 And I found some example too , but the problem is, almost all the examples uses 'xjc' tool to do this.我也找到了一些例子,但问题是,几乎所有的例子都使用“xjc”工具来做到这一点。 But I want a way to do this through my java code.但我想要一种通过我的 java 代码来做到这一点的方法。

Os this possible?这可能吗?
if yes, I'm thinking something like this, from my java code如果是的话,我正在考虑这样的事情,从我的 Java 代码

  • load the .xsd file加载 .xsd 文件
  • generate the .xml生成 .xml
  • save the .xml file保存 .xml 文件

Can someone direct me to a good resource and or tell me if my thinking is wrong有人可以指导我找到一个好的资源,或者告诉我我的想法是否错误

I've had good experiences using XMLBeans , however I've always had the XSD available at compile time.我在使用XMLBeans 方面有很好的经验,但是我在编译时总是可以使用 XSD。 It integrates nicely with Maven (plus potentially other build systems).它与 Maven(以及潜在的其他构建系统)很好地集成在一起。 The compilation produces a series of Java classes that can be used to construct an XML document that conforms to the XSD or process an XML file you've received.编译会生成一系列 Java 类,这些类可用于构造符合 XSD 的 XML 文档或处理您收到的 XML 文件。

You can potentially do some runtime processing of an XSD using the org.apache.xmlbeans.XmlBeans.compileXsd class, but I've never experimented with it.您可以使用org.apache.xmlbeans.XmlBeans.compileXsd类潜在地对 XSD 进行一些运行时处理,但我从未尝试过它。 Just seen a reference from an FAQ.刚刚从常见问题解答中看到了一个参考。

I think the main problem is that to do it in a clean way you should have classes reflecting your xsd.我认为主要问题是要以干净的方式进行操作,您应该让类反映您的 xsd。 Xsd defines a data model, so the important part is to recreate it with classes. Xsd 定义了一个数据模型,所以重要的部分是用类重新创建它。 If you want to do it dynamically it could be rather difficult.如果你想动态地做它可能会相当困难。 If you want to do it at compile time- jaxb is the way to go.如果你想在编译时做 - jaxb 是要走的路。 There is very interesting article talking about problems related with parsing xml (it goes from a different perspective than you describe), but I think there is a wealth of knowledge to be learned from here:有一篇非常有趣的文章讨论了与解析 xml 相关的问题(它从与您描述的不同的角度出发),但我认为从这里可以学到很多知识:

http://elegantcode.com/2010/08/07/dont-parse-that-xml/ http://elegantcode.com/2010/08/07/dont-parse-that-xml/

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

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