猿问

如何使用 Java 从 XSD 生成 XML 数据?

在我正在处理的应用程序中,我需要从 XSD 生成示例数据(XML 实例)。我有 a 形式的 XSD String,需要再次生成各自的XMLas String。


例如考虑下面的 XSD


<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:element name="Employee">

    <xs:complexType>

      <xs:sequence>

        <xs:element type="xs:string" name="name"/>

        <xs:element type="xs:byte" name="age"/>

        <xs:element type="xs:string" name="role"/>

        <xs:element type="xs:string" name="gender"/>

      </xs:sequence>

    </xs:complexType>

  </xs:element>

</xs:schema>

我想生成


<Employee>

  <name>string</name>

  <age>2</age>

  <role>string</role>

  <gender>string</gender>

</Employee>

搜索了一段时间后,发现了各种在线工具可以做到这一点,但我希望能够使用Java来实现它。还有像 Eclipse、Netbeans、IntelliJ 这样的 IDE 能够实现所需的功能,除了它们依赖于作为文件提供的 XSD。


经过一番搜索,似乎其中大多数都使用Apache XMLBeans。


我尝试按照安装指南设置所有提到的环境变量,如下所示


export XMLBEANS_HOME=/home/user/Programs/xmlbeans-3.1.0

PATH=$PATH:$XMLBEANS_HOME/bin

export CLASSPATH=$XMLBEANS_HOME/lib/xmlbeans-3.1.0.jar:$CLASSPATH

export XMLBEANS_LIB=/home/user/Programs/xmlbeans-3.1.0/lib/xmlbeans-3.1.0.jar

毕竟如果我运行下面给出的命令

./xsd2inst ../../Schema.xsd

我收到错误

错误:无法找到或加载主类 org.apache.xmlbeans.impl.xsd2inst.SchemaInstanceGenerator

问题:

  1. 我该怎么做才能修复此错误?

  2. 如果我得到这个工作,我可能可以在将 XSD 字符串写入文件并将其作为参数传递给命令后从 Java 进程调用此命令,就像我上面显示的那样。但我不认为这是一个优雅的解决方案,还有其他方法可以完成我提到的吗?

笔记:

  1. 我不能使用任何商业产品/库。

  2. 我知道使用 JAXB,但这将需要我为我想要生成数据的类型创建一个 POJO,因为 XSD 数据是动态的,我无法重用这些 POJO,即使我创造它。


繁星点点滴滴
浏览 129回答 1
1回答

慕的地6264312

深入挖掘后,发现XMLBEANS_LIB错误设置了环境变量值。期望XMLBEANS_LIB指向libXML Beans 分发的目录,而不是xmlbeans-3.1.0.jar。所以正确的价值是&nbsp;export XMLBEANS_LIB=/home/user/Programs/xmlbeans-3.1.0/lib我能够使用以下代码使用 XSD(作为字符串给出)生成 XMLInstance(作为字符串)。import org.apache.xmlbeans.SchemaType;import org.apache.xmlbeans.SchemaTypeSystem;import org.apache.xmlbeans.XmlBeans;import org.apache.xmlbeans.XmlException;import org.apache.xmlbeans.XmlObject;import org.apache.xmlbeans.XmlOptions;import org.apache.xmlbeans.impl.xsd2inst.SampleXmlUtil;import org.apache.xmlbeans.impl.xsd2inst.SchemaInstanceGenerator;import java.util.ArrayList;import java.util.List;public class XmlInstanceGeneratorImpl {&nbsp; private static final Logger logger = LogManager.getLogger(XmlInstanceGeneratorImpl.class);&nbsp; /**&nbsp; &nbsp;* Specifies if network downloads are enabled for imports and includes.&nbsp; &nbsp;* Default value is {@code false}&nbsp; &nbsp;*/&nbsp; private static final boolean ENABLE_NETWORK_DOWNLOADS = false;&nbsp; /**&nbsp; &nbsp;* disable particle valid (restriction) rule&nbsp; &nbsp;* Default value is {@code false}&nbsp; &nbsp;*/&nbsp; private static final boolean NO_PVR = false;&nbsp; /**&nbsp; &nbsp;* disable unique particle attribution rule.&nbsp; &nbsp;* Default value is {@code false}&nbsp; &nbsp;*/&nbsp; private static final boolean NO_UPA = false;&nbsp; public String generateXmlInstance(String xsdAsString, String elementToGenerate){&nbsp; &nbsp; return generateXmlInstance(xsdAsString, elementToGenerate, ENABLE_NETWORK_DOWNLOADS, NO_PVR, NO_UPA);&nbsp; }&nbsp; public String generateXmlInstance(String xsAsString, String elementToGenerate, boolean enableDownloads,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; boolean noPvr, boolean noUpa){&nbsp; &nbsp; List<XmlObject> schemaXmlObjects = new ArrayList<>();&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; schemaXmlObjects.add(XmlObject.Factory.parse(xsAsString));&nbsp; &nbsp; } catch (XmlException e) {&nbsp; &nbsp; &nbsp; logger.error("Error Occured while Parsing Schema",e);&nbsp; &nbsp; }&nbsp; &nbsp; XmlObject[] xmlObjects = schemaXmlObjects.toArray(new XmlObject[1]);&nbsp; &nbsp; SchemaInstanceGenerator.Xsd2InstOptions options = new SchemaInstanceGenerator.Xsd2InstOptions();&nbsp; &nbsp; options.setNetworkDownloads(enableDownloads);&nbsp; &nbsp; options.setNopvr(noPvr);&nbsp; &nbsp; options.setNoupa(noUpa);&nbsp; &nbsp; return xsd2inst(xmlObjects, elementToGenerate, options);&nbsp; }&nbsp; private String xsd2inst(XmlObject[] schemas, String rootName, SchemaInstanceGenerator.Xsd2InstOptions options){&nbsp; &nbsp; SchemaTypeSystem schemaTypeSystem = null;&nbsp; &nbsp; if (schemas.length > 0) {&nbsp; &nbsp; &nbsp; XmlOptions compileOptions = new XmlOptions();&nbsp; &nbsp; &nbsp; if (options.isNetworkDownloads())&nbsp; &nbsp; &nbsp; &nbsp; compileOptions.setCompileDownloadUrls();&nbsp; &nbsp; &nbsp; if (options.isNopvr())&nbsp; &nbsp; &nbsp; &nbsp; compileOptions.setCompileNoPvrRule();&nbsp; &nbsp; &nbsp; if (options.isNoupa())&nbsp; &nbsp; &nbsp; &nbsp; compileOptions.setCompileNoUpaRule();&nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; schemaTypeSystem = XmlBeans.compileXsd(schemas, XmlBeans.getBuiltinTypeSystem(), compileOptions);&nbsp; &nbsp; &nbsp; } catch (XmlException e) {&nbsp; &nbsp; &nbsp; &nbsp; logger.error("Error occurred while compiling XSD",e);&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; if (schemaTypeSystem == null) {&nbsp; &nbsp; &nbsp; throw new RuntimeException("No Schemas to process.");&nbsp; &nbsp; }&nbsp; &nbsp; SchemaType[] globalElements = schemaTypeSystem.documentTypes();&nbsp; &nbsp; SchemaType elem = null;&nbsp; &nbsp; for (SchemaType globalElement : globalElements) {&nbsp; &nbsp; &nbsp; if (rootName.equals(globalElement.getDocumentElementName().getLocalPart())) {&nbsp; &nbsp; &nbsp; &nbsp; elem = globalElement;&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; if (elem == null) {&nbsp; &nbsp; &nbsp; throw new RuntimeException("Could not find a global element with name \"" + rootName + "\"");&nbsp; &nbsp; }&nbsp; &nbsp; // Now generate it and return the result&nbsp; &nbsp; return SampleXmlUtil.createSampleForType(elem);&nbsp; }}
随时随地看视频慕课网APP

相关分类

Java
我要回答