亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用 Java 從 XSD 生成 XML 數據?

如何使用 Java 從 XSD 生成 XML 數據?

繁星點點滴滴 2023-04-13 14:21:24
在我正在處理的應用程序中,我需要從 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.0PATH=$PATH:$XMLBEANS_HOME/binexport CLASSPATH=$XMLBEANS_HOME/lib/xmlbeans-3.1.0.jar:$CLASSPATHexport XMLBEANS_LIB=/home/user/Programs/xmlbeans-3.1.0/lib/xmlbeans-3.1.0.jar畢竟如果我運行下面給出的命令./xsd2inst ../../Schema.xsd我收到錯誤錯誤:無法找到或加載主類 org.apache.xmlbeans.impl.xsd2inst.SchemaInstanceGenerator問題:我該怎么做才能修復此錯誤?如果我得到這個工作,我可能可以在將 XSD 字符串寫入文件并將其作為參數傳遞給命令后從 Java 進程調用此命令,就像我上面顯示的那樣。但我不認為這是一個優雅的解決方案,還有其他方法可以完成我提到的嗎?筆記:我不能使用任何商業產品/庫。我知道使用 JAXB,但這將需要我為我想要生成數據的類型創建一個 POJO,因為 XSD 數據是動態的,我無法重用這些 POJO,即使我創造它。
查看完整描述

1 回答

?
慕的地6264312

TA貢獻1817條經驗 獲得超6個贊

深入挖掘后,發現XMLBEANS_LIB錯誤設置了環境變量值。期望XMLBEANS_LIB指向libXML Beans 分發的目錄,而不是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);

  }

}



查看完整回答
反對 回復 2023-04-13
  • 1 回答
  • 0 關注
  • 211 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號