在最新版本的免费和开源 Eclipse IDE 中,您可以从 DTD 和 XSD 文件生成 XML 文档。右键单击给定的 *.dtd 或 *.xsd 文件并选择“生成 -> XML 文件...”。您可以选择要生成的根元素以及是否应生成可选属性和元素。
我可以使用这个无头(不启动 Eclipse)吗?
您可以创建一个无头RCP应用程序,其中仅包含执行实际生成所需的那些插件。这些主要是 WTP 插件,其中包含管理扩展点等所需的几个核心插件。
RCP 应用程序可以从命令行运行,并传递要生成的架构的参数和输出文件名。它缺少您在生产实施中可能需要的大部分验证,但向您展示了如何完成它。它还将字符集硬编码为 UTF-8,您可以扩展参数处理以使其成为可选参数或其他内容。
下面的代码片段可以合并到一个新的无头 RCP 应用程序中。要创建 RCP 应用程序,首先创建一个新的插件项目:
在项目中,您应该会看到一个Application
类,将下面的 Java 内容复制到源的start()
方法中Application
(以及文件顶部的导入)。
导入 java.io.ByteArrayOutputStream;导入java.io.File;导入 java.io.FileInputStream;导入 java.io.FileOutputStream;导入 java.io.FileWriter;导入 java.net.URI;导入 java.net.URL;
导入 org.eclipse.core.internal.utils.FileUtil;导入 org.eclipse.core.runtime.Platform;导入 org.eclipse.emf.ecore.plugin.EcorePlugin;导入 org.eclipse.equinox.app.IApplication;导入 org.eclipse.equinox.app.IApplicationContext;导入 org.eclipse.wst.xml.core.internal.contentmodel.CMDocument;导入 org.eclipse.wst.xml.ui.internal.wizards.NewXMLGenerator;
public Object start(IApplicationContext context) throws Exception { String[] args = Platform.getCommandLineArgs();
String schemaFileName = args[0];// e.g. "C:\test\test.xsd"
String xmlFileName = args[1];// e.g. "C:\test\test.xml"
String rootName = args[2];//"myTestRoot";
String charsetName = "UTF-8";
try {
//get the URI as a full URL path
URI schemaUri = new File(schemaFileName).toURI();
schemaFileName = schemaUri.toURL().toString();
//TODO handle any errorInfo set into this array
String[] errorInfo = new String[2];
CMDocument cmDocument = NewXMLGenerator.createCMDocument(schemaFileName,
errorInfo);
NewXMLGenerator generator = new NewXMLGenerator(schemaFileName,
cmDocument);
generator.setRootElementName(rootName);
ByteArrayOutputStream out = generator.createXMLDocument(xmlFileName,
charsetName);
//output the content to the file.
File outFile = new File(xmlFileName);
outFile.getParentFile().mkdirs();
FileWriter writer = new FileWriter(outFile);
writer.write(out.toString(charsetName));
writer.flush();
writer.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return IApplication.EXIT_OK;
}
要创建独立应用程序,您还需要创建Product Configuration。
您现在需要导出 RCP 应用程序。
您现在应该有一个独立的应用程序,您可以像调用任何其他应用程序一样调用它,传递命令行参数以从模式生成 XML 文件。
预期的参数依次为:
注意此过程只会从单个模式生成文件,如果您的模式引用其他模式,它当前将失败。可以扩展该过程以获取列出所有引用模式位置的属性文件,并将它们解析为目录贡献,以便该过程可以解析模式。下面是一些关于如何以及为什么要这样做的说明。
如果我有机会,我会考虑实施这个并相应地更新我的答案。
例如,如果您有一个 Spring 模式,您可能希望在模式文件中包含各种 Spring 命名空间模式。在 Eclipse 中,目录贡献提供了一种将这些模式 ID 映射到模式文件位置的方法,以便可以对其进行解析。如果您有它们的插件,它们可以与应用程序捆绑在一起并定义目录贡献(有关贡献它们的指针,请参见帮助)。
如果您没有可用的目录贡献,则该过程将改为在属性文件中定义键值对以引用驱动器上的架构位置。
示例内容:
http://www.springframework.org/schema/beans=c:\\schema\\spring-beans.xsd
http://www.springframework.org/schema/tool=c:\\schema\\spring-tool.xsd