问题描述:

The goal of my application is to create XML-config files which are conformant to a XSD file.

My plan to achieve this is the following:

1. I create an ecore model out of the xsd file

2. From this ecore model i generate java classes (via genmodel)

3. The classes which are needed in the current config instance i fill with values

4. Now i create somehow a XML file out of that.

From the conf.xsd in step 2 three different folders filled with java classes where created: Conf, Conf.impl and Conf.util. Via ConfFactoryImpl.init() I created the ConfFactory. And now, according to the following article (How to convert an XMI model-instance of Ecore to XML of the given XSD?) I can use XMLResource somehow to creae a XML file, if I understood this correctly. But I'm still struggling with this one. My JAVA is quite rusty (havent used it for the last couple of years), so I would be helpful for any hints.

网友答案:

This may be helpful. It's an example of creating XML files in java from an existing .XSD

The XSD:

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
 xmlns:jxb="http://java.sun.com/xml/ns/jaxb"
 jxb:version="2.0">

<xsd:element name="Greetings" type="GreetingListType"/>
 <xsd:complexType name="GreetingListType">
  <xsd:sequence>
   <xsd:element name="Greeting" type="GreetingType"
         maxOccurs="unbounded"/>
  </xsd:sequence>
 </xsd:complexType>
 <xsd:complexType name="GreetingType">
  <xsd:sequence>
   <xsd:element name="Text" type="xsd:string"/>
  </xsd:sequence>
  <xsd:attribute name="language" type="xsd:language"/>
</xsd:complexType>

</xsd:schema>

Java class:

import java.util.*;
import javax.xml.bind.*;
import hello.*;

public class Hello {

private ObjectFactory of;
private GreetingListType grList;

public Hello(){
 of = new ObjectFactory();
 grList = of.createGreetingListType();
}

 public void make( String t, String l ){
   GreetingType g = of.createGreetingType();
   g.setText( t );
   g.setLanguage( l );
   grList.getGreeting().add( g );
 }

public void marshal() {
  try {
       JAXBElement<GreetingListType> gl =
        of.createGreetings( grList );
        JAXBContext jc = JAXBContext.newInstance( "hello" );
        Marshaller m = jc.createMarshaller();
         m.marshal( gl, System.out );
       } catch( JAXBException jbe ){
    // ...
  }
}

}

Example:

Hello h = new Hello();
h.make( "Bonjour, madame", "fr" ); 
h.make( "Hey, you", "en" ); 
h.marshal();

Output:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Greetings>
<Greeting language="fr">
<Text>Bonjour, madame</Text>
</Greeting>
<Greeting language="en">
<Text>Hey, you</Text>
相关阅读:
Top