[英]How to generate XML data from XSD using Java?
In an application I'm working on I need to generate sample data (XML instance) from XSD.在我正在处理的应用程序中,我需要从 XSD 生成示例数据(XML 实例)。 I have XSD in the form of a
String
and need to generate respective XML
as String
again.我有一个
String
形式的 XSD,需要再次将相应的XML
成为String
。
For example consider the below XSD例如考虑下面的 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>
I want to generate我想生成
<Employee>
<name>string</name>
<age>2</age>
<role>string</role>
<gender>string</gender>
</Employee>
After searching for a while came across various online tools which does this, but I want to be able to achieve it using Java .搜索了一段时间后,遇到了各种执行此操作的在线工具,但我希望能够使用Java实现它。 Also there are IDEs like Eclipse, Netbeans, IntelliJ which are able to achieve the desired functionality, except that they rely on XSD to be given as a File.
也有像 Eclipse、Netbeans、IntelliJ 这样的 IDE,它们能够实现所需的功能,但它们依赖 XSD 作为文件提供。
After bit of searching around seems like most of these use Apache XMLBeans .经过一番搜索,似乎其中大多数都使用Apache XMLBeans 。
I tried following the installation guide and setup all the environment variables mentioned like below我尝试按照安装指南并设置下面提到的所有环境变量
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
After all this if I run the command given below毕竟,如果我运行下面给出的命令
./xsd2inst ../../Schema.xsd
I get error我得到错误
Error: Could not find or load main class org.apache.xmlbeans.impl.xsd2inst.SchemaInstanceGenerator
错误:无法找到或加载主类 org.apache.xmlbeans.impl.xsd2inst.SchemaInstanceGenerator
Questions:问题:
Note:笔记:
After digging in a little bit, realised the environment variable value for XMLBEANS_LIB
is wrongly set.稍加挖掘后,发现
XMLBEANS_LIB
的环境变量值设置错误。 The XMLBEANS_LIB
expects to be pointed to the lib
directory of the XML Beans distribution not to xmlbeans-3.1.0.jar
. XMLBEANS_LIB
期望指向 XML Beans 发行版的lib
目录,而不是指向xmlbeans-3.1.0.jar
。 So the correct value for that is所以正确的值是
export XMLBEANS_LIB=/home/user/Programs/xmlbeans-3.1.0/lib
I was able to generate the XMLInstance (as a String) using XSD ( given as String) using the below code.我能够使用以下代码使用 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 {
private static final Logger logger = LogManager.getLogger(XmlInstanceGeneratorImpl.class);
/**
* Specifies if network downloads are enabled for imports and includes.
* Default value is {@code false}
*/
private static final boolean ENABLE_NETWORK_DOWNLOADS = false;
/**
* disable particle valid (restriction) rule
* Default value is {@code false}
*/
private static final boolean NO_PVR = false;
/**
* disable unique particle attribution rule.
* Default value is {@code false}
*/
private static final boolean NO_UPA = false;
public String generateXmlInstance(String xsdAsString, String elementToGenerate){
return generateXmlInstance(xsdAsString, elementToGenerate, ENABLE_NETWORK_DOWNLOADS, NO_PVR, NO_UPA);
}
public String generateXmlInstance(String xsAsString, String elementToGenerate, boolean enableDownloads,
boolean noPvr, boolean noUpa){
List<XmlObject> schemaXmlObjects = new ArrayList<>();
try {
schemaXmlObjects.add(XmlObject.Factory.parse(xsAsString));
} catch (XmlException e) {
logger.error("Error Occured while Parsing Schema",e);
}
XmlObject[] xmlObjects = schemaXmlObjects.toArray(new XmlObject[1]);
SchemaInstanceGenerator.Xsd2InstOptions options = new SchemaInstanceGenerator.Xsd2InstOptions();
options.setNetworkDownloads(enableDownloads);
options.setNopvr(noPvr);
options.setNoupa(noUpa);
return xsd2inst(xmlObjects, elementToGenerate, options);
}
private String xsd2inst(XmlObject[] schemas, String rootName, SchemaInstanceGenerator.Xsd2InstOptions options){
SchemaTypeSystem schemaTypeSystem = null;
if (schemas.length > 0) {
XmlOptions compileOptions = new XmlOptions();
if (options.isNetworkDownloads())
compileOptions.setCompileDownloadUrls();
if (options.isNopvr())
compileOptions.setCompileNoPvrRule();
if (options.isNoupa())
compileOptions.setCompileNoUpaRule();
try {
schemaTypeSystem = XmlBeans.compileXsd(schemas, XmlBeans.getBuiltinTypeSystem(), compileOptions);
} catch (XmlException e) {
logger.error("Error occurred while compiling XSD",e);
}
}
if (schemaTypeSystem == null) {
throw new RuntimeException("No Schemas to process.");
}
SchemaType[] globalElements = schemaTypeSystem.documentTypes();
SchemaType elem = null;
for (SchemaType globalElement : globalElements) {
if (rootName.equals(globalElement.getDocumentElementName().getLocalPart())) {
elem = globalElement;
break;
}
}
if (elem == null) {
throw new RuntimeException("Could not find a global element with name \"" + rootName + "\"");
}
// Now generate it and return the result
return SampleXmlUtil.createSampleForType(elem);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.