Génération du xml à partir du XSD

Génération du code xml à partir d'un XSD

Pour générer du XML à partir du XSD, il faut utiliser la librairie Apache XML Bean. Voici le code :

 1import org.apache.xmlbeans.SchemaType;
 2import org.apache.xmlbeans.SchemaTypeSystem;
 3import org.apache.xmlbeans.XmlBeans;
 4import org.apache.xmlbeans.XmlException;
 5import org.apache.xmlbeans.XmlObject;
 6import org.apache.xmlbeans.XmlOptions;
 7import org.apache.xmlbeans.impl.xsd2inst.SampleXmlUtil;
 8import org.apache.xmlbeans.impl.xsd2inst.SchemaInstanceGenerator;
 9
10import java.util.ArrayList;
11import java.util.List;
12
13public class XmlInstanceGeneratorImpl {
14  private static final Logger logger = LogManager.getLogger(XmlInstanceGeneratorImpl.class);
15
16  /**
17   * Specifies if network downloads are enabled for imports and includes.
18   * Default value is {@code false}
19   */
20  private static final boolean ENABLE_NETWORK_DOWNLOADS = false;
21
22  /**
23   * disable particle valid (restriction) rule
24   * Default value is {@code false}
25   */
26  private static final boolean NO_PVR = false;
27
28  /**
29   * disable unique particle attribution rule.
30   * Default value is {@code false}
31   */
32  private static final boolean NO_UPA = false;
33
34
35  public String generateXmlInstance(String xsdAsString, String elementToGenerate){
36    return generateXmlInstance(xsdAsString, elementToGenerate, ENABLE_NETWORK_DOWNLOADS, NO_PVR, NO_UPA);
37  }
38
39
40  public String generateXmlInstance(String xsAsString, String elementToGenerate, boolean enableDownloads,
41                                    boolean noPvr, boolean noUpa){
42    List<XmlObject> schemaXmlObjects = new ArrayList<>();
43    try {
44      schemaXmlObjects.add(XmlObject.Factory.parse(xsAsString));
45    } catch (XmlException e) {
46      logger.error("Error Occured while Parsing Schema",e);
47    }
48    XmlObject[] xmlObjects = schemaXmlObjects.toArray(new XmlObject[1]);
49    SchemaInstanceGenerator.Xsd2InstOptions options = new SchemaInstanceGenerator.Xsd2InstOptions();
50    options.setNetworkDownloads(enableDownloads);
51    options.setNopvr(noPvr);
52    options.setNoupa(noUpa);
53    return xsd2inst(xmlObjects, elementToGenerate, options);
54  }
55
56  private String xsd2inst(XmlObject[] schemas, String rootName, SchemaInstanceGenerator.Xsd2InstOptions options){
57    SchemaTypeSystem schemaTypeSystem = null;
58    if (schemas.length > 0) {
59      XmlOptions compileOptions = new XmlOptions();
60      if (options.isNetworkDownloads())
61        compileOptions.setCompileDownloadUrls();
62      if (options.isNopvr())
63        compileOptions.setCompileNoPvrRule();
64      if (options.isNoupa())
65        compileOptions.setCompileNoUpaRule();
66      try {
67        schemaTypeSystem = XmlBeans.compileXsd(schemas, XmlBeans.getBuiltinTypeSystem(), compileOptions);
68      } catch (XmlException e) {
69        logger.error("Error occurred while compiling XSD",e);
70      }
71    }
72    if (schemaTypeSystem == null) {
73      throw new RuntimeException("No Schemas to process.");
74    }
75
76    SchemaType[] globalElements = schemaTypeSystem.documentTypes();
77    SchemaType elem = null;
78    for (SchemaType globalElement : globalElements) {
79      if (rootName.equals(globalElement.getDocumentElementName().getLocalPart())) {
80        elem = globalElement;
81        break;
82      }
83    }
84    if (elem == null) {
85      throw new RuntimeException("Could not find a global element with name \"" + rootName + "\"");
86    }
87    // Now generate it and return the result
88    return SampleXmlUtil.createSampleForType(elem);
89  }
90}

Code trouvé ici

Pour le faire avec maven :

 1<project>
 2  <!-- ... -->
 3    <build>
 4    <plugins>
 5      <plugin>
 6        <groupId>org.codehaus.mojo</groupId>
 7        <artifactId>exec-maven-plugin</artifactId>
 8        <version>3.0.0</version>
 9        <executions>
10          <execution>
11            <goals>
12              <goal>java</goal>
13            </goals>
14          </execution>
15        </executions>
16        <configuration>
17          <includeProjectDependencies>false</includeProjectDependencies>
18          <includePluginDependencies>true</includePluginDependencies>
19          <mainClass>org.apache.xmlbeans.impl.inst2xsd.Inst2Xsd</mainClass>
20          <arguments>
21            <!-- Add as many arguments as you need -->
22            <argument>-outDir</argument>
23            <argument>${project.build.outputDirectory}</argument>
24            <argument>-validate</argument>
25            <argument>${project.basedir}/src/main/resources/food-menu.xml</argument>
26          </arguments>
27        </configuration>
28        <dependencies>
29          <dependency>
30            <groupId>org.apache.xmlbeans</groupId>
31            <artifactId>xmlbeans</artifactId>
32            <version>3.1.0</version>
33          </dependency>
34        </dependencies>
35      </plugin>
36    </plugins>
37  </build>
38  <!-- ... -->
39</project>

Code trouvé ici