[英]How to generate XML data from XSD using Java?
在我正在處理的應用程序中,我需要從 XSD 生成示例數據(XML 實例)。 我有一個String
形式的 XSD,需要再次將相應的XML
成為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
問題:
筆記:
稍加挖掘后,發現XMLBEANS_LIB
的環境變量值設置錯誤。 XMLBEANS_LIB
期望指向 XML Beans 發行版的lib
目錄,而不是指向xmlbeans-3.1.0.jar
。 所以正確的值是
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 {
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.