-3

I have an XML data like

<Data><CustomerDetails><CustomerName>ABCD</CustomerName><CusomerACCTNumber>12121212</CusomerACCTNumber></CustomerDetails><BillDetails><BillTxDetails><BillID>121212</BillID><BillDate>12-May-2015</BillDate><Time>12:55AM</Time></BillTxDetails><BillTxDetails><BillID>121212</BillID><BillDate>12-May-2015</BillDate><Time>5:55AM</Time></BillTxDetails></BillDetails></Data>

how to create xsd File using java? and how to create java class (pojo/bean) for above xml data? I tried this way

public class CustomerDetails {
  private String CustomerName;
  private String CusomerACCTNumber; 
  // ==> setters and getters
}

public class BillTxDetails {
  private String BillID;
  private String BillDate;
  private String Time;
  // ==> setters and getters
} 

public static void main(String ...) {
  Class[] c = new Class[] { CustomerDetails.class,  BillTxDetails.class };
  JAXBContext jc =JAXBContext.newInstance(Data.class);
  jc.generateSchema(new SchemaOutputResolver() {

    @Override 
    public Result createOutput(String namespaceUri, String suggestedFileName) throws IOException {
      StreamResult result = new StreamResult(System.out);
      result.setSystemId(suggestedFileName); 
      return result 
    }
  }); 
}

But still iam not getting in XSD root element Thanks

Community
  • 1
  • 1
Raj
  • 677
  • 3
  • 8
  • 16
  • You have an XML file. This does not look like ans XSD file ... – Sirko Jul 14 '15 at 10:28
  • Think he meant he has an XML from which he wants to build an xsd. OP please clarify your question – Constantin Jul 14 '15 at 10:29
  • This is an XMl data to be generate an XSD using java. – Raj Jul 14 '15 at 10:33
  • Normally, the XSD should have been created BEFORE the XML as the purpose of an XSD file is to validate your XML. With this in mind, you can try using a tool like trang to create a template of the XSD (from an existing XML snippet) and then modify your XSD by hand, adding any extra validation rules to it. No tool will be able to know exactly what those rules should be, such as datatypes, max lengths, required vs optional and so on – Constantin Jul 14 '15 at 11:42
  • Thanks, In my concern First i am creating Sample XML Data and classes (say JaxB classes) based on that java classes creating XSD File – Raj Jul 14 '15 at 11:49
  • What is your starting point? XML, or Java classes??? – Constantin Jul 14 '15 at 12:06
  • creating xml manually (reference purpose how the structure) and based on that writing java classes to generate xsd file – Raj Jul 14 '15 at 12:29

4 Answers4

1

Your starting point should be the XSD file. You can use an online XSD generator to build one from your XML: http://www.freeformatter.com/xsd-generator.html

You can also use a tool like Trang http://www.thaiopensource.com/relaxng/trang.html

Or if you want to build your own XSD generator, look at this link Generate XSD programmatically in java

Finally, here are some JAXB examples that may help ...

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.SchemaOutputResolver;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.transform.Result;
import javax.xml.transform.stream.StreamResult;

import org.xml.sax.InputSource;

import com.sun.codemodel.JCodeModel;
import com.sun.tools.xjc.api.S2JJAXBModel;
import com.sun.tools.xjc.api.SchemaCompiler;
import com.sun.tools.xjc.api.XJC;

public class Demo {

  public static void buildClasses(File xsdFile) throws IOException {
    SchemaCompiler sc = XJC.createSchemaCompiler();
      sc.parseSchema(new InputSource(xsdFile.toURI().toString()));
      S2JJAXBModel model = sc.bind();

      JCodeModel cm = model.generateCode(null, null);
      cm.build(new File("."));
  }

  public static final void printFile(File file) throws IOException {
    BufferedReader reader = new BufferedReader(new FileReader(file));
    String line = null;
    while ((line = reader.readLine()) != null) {
      System.out.println(line);
    }   
    reader.close();
  }

  public static void main(String[] args)  {
    try {

      Example example;
      File xmlFile = new File("example.xml");
      File xsdFile = new File("example.xsd");
      JAXBContext jaxbContext = JAXBContext.newInstance(Example.class);

      ////////////////////////////////////////////////////////////////////////////////////
      // USE THIS CODE TO BUILD YOUR XML FROM AN EXISTING INSTANTIATED JAVA CLASS 
      ////////////////////////////////////////////////////////////////////////////////////    
      System.out.println("===========================================");  
      example = new Example();
      example.id = 123;
      example.name = "Constantin";
      example.dob = new SimpleDateFormat("yyyy-MM-dd").parse("1971-01-13");

      Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
      jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
      jaxbMarshaller.marshal(example, xmlFile);
      printFile(xmlFile);
      System.out.println("===========================================");  

      ////////////////////////////////////////////////////////////////////////////////////
      // USE THIS CODE TO BUILD YOUR XSD FROM AN EXISTING JAVA CLASS 
      ////////////////////////////////////////////////////////////////////////////////////  
      System.out.println("===========================================");  
      jaxbContext.generateSchema(new SchemaOutputResolver() {
        @Override
        public Result createOutput(String namespaceUri, String suggestedFileName) throws IOException {
          StreamResult result = new StreamResult(new FileOutputStream(xsdFile));
          result.setSystemId(xsdFile.getAbsolutePath());
          return result;
        }
      });
      printFile(xsdFile);
      System.out.println("===========================================");  

      ////////////////////////////////////////////////////////////////////////////////////
      // USE THIS CODE TO INSTANTIATE A JAVA CLASS FROM AN EXISTING XML FILE
      ////////////////////////////////////////////////////////////////////////////////////    
      System.out.println("===========================================");     
      Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
      example = (Example) jaxbUnmarshaller.unmarshal(xmlFile);
      System.out.println("[" + example.getId() + "][" + example.getName() + "][" + example.getDOB() + "]");
      System.out.println("===========================================");  


      ////////////////////////////////////////////////////////////////////////////////////
      // USE THIS CODE TO BUILD JAVA CLASSES FROM EXISTING XSD FILE 
      ////////////////////////////////////////////////////////////////////////////////////    
      buildClasses(xsdFile);      
    } 
    catch (JAXBException e) {
      e.printStackTrace();
    } 
    catch (IOException e) {
      e.printStackTrace();
    } 
    catch (ParseException e) {
      e.printStackTrace();
    }
  }
}

@XmlRootElement
class Example {
  int id;
  String name;
  Date dob;

  @XmlElement
  public void setId(int id) {
    this.id = id;
  }

  public int getId() {
    return id;
  }

  @XmlElement
  public void setName(String name) {
    this.name = name;
  }

  public String getName() {
    return name;
  }

  @XmlElement
  public void setDOB(Date dob) {
    this.dob = dob;
  } 

  public Date getDOB() {
    return dob;
  }
}

You may need to download some dependency jars to make this work : https://jaxb.java.net/2.2.11/

Community
  • 1
  • 1
Constantin
  • 1,506
  • 10
  • 16
  • thanks constantin, but Here i need to be create java class for above XML data ie. mapping class for xml data. Using that java class need to generate XSD File like Class[] c = {CustomerDetails.class,FinancialAdvisorContactDetails.class,PolicyDetails.class,PremiumDetails.class,PremiumReceipt.class}; JAXBContext jc = JAXBContext.newInstance(c,null); – Raj Jul 14 '15 at 10:37
  • I added a link to a previous post. Did you try to search for an existing answer before asking it again? Also, change your question to read "XML" instead of XSD: I have an *XML* file data like – Constantin Jul 14 '15 at 10:42
  • Created separate java class for each tag ... for example for CustomerDetails created CustomerDetails class having properites CustomerName and CusomerACCTNumber. finally after executing iam not getting root tag in xsd that is instead getting .? how to get root element using java – Raj Jul 14 '15 at 10:44
  • Try showing us your code so we may see what you're doing wrong – Constantin Jul 14 '15 at 10:46
1

if you are using eclipse u can do following.

  • create an XML file in any project.
  • right click on XML file click generate schema.
  • give it a name

i got the following when trying to generate schema from your XML

<?xml version="1.0" encoding="UTF-8"?><xsd:schema   xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <xsd:element name="BillDetails">
    <xsd:complexType>
      <xsd:sequence>
        <xsd:element maxOccurs="unbounded" ref="BillTxDetails"/>
      </xsd:sequence>
    </xsd:complexType>
  </xsd:element>
  <xsd:element name="Data">
    <xsd:complexType>
      <xsd:sequence>
        <xsd:element ref="CustomerDetails"/>
        <xsd:element ref="BillDetails"/>
      </xsd:sequence>
    </xsd:complexType>
  </xsd:element>
  <xsd:element name="CustomerDetails">
    <xsd:complexType>
      <xsd:sequence>
        <xsd:element ref="CustomerName"/>
        <xsd:element ref="CusomerACCTNumber"/>
      </xsd:sequence>
    </xsd:complexType>
  </xsd:element>
  <xsd:element name="Time" type="xsd:string"/>
  <xsd:element name="BillTxDetails">
    <xsd:complexType>
      <xsd:sequence>
        <xsd:element ref="BillID"/>
        <xsd:element ref="BillDate"/>
        <xsd:element ref="Time"/>
      </xsd:sequence>
    </xsd:complexType>
  </xsd:element>
  <xsd:element name="BillID" type="xsd:string"/>
  <xsd:element name="BillDate" type="xsd:string"/>
  <xsd:element name="CustomerName" type="xsd:string"/>
  <xsd:element name="CusomerACCTNumber" type="xsd:string"/>
  </xsd:schema>

then right click on xsd and select generate java classes

0

I tried this way public class CustomerDetails{private String CustomerName;private String CusomerACCTNumber;==>setters and getters}public class BillTxDetails{private String BillID;private String BillDate;private String Time;==>setters and getters} public static void main(Sring ....){Class[] c = {CustomerDetails.class, BillTxDetails.class};JAXBContext jc =JAXBContext.newInstance(Data.class);jc.generateSchema(new SchemaOutputResolver() {@Override public Result createOutput(String namespaceUri, String suggestedFileName) throws IOException {StreamResult result = new StreamResult(System.out);result.setSystemId(suggestedFileName); return result }}); But still iam not getting in XSD root element

Raj
  • 677
  • 3
  • 8
  • 16
0

Finally I solved Here is the complete reference

Raj
  • 677
  • 3
  • 8
  • 16
  • doesn't it make more sense to build your xsd from the xml (using an online tool or, if you must do it programmatically) using trang? From there, you can build your classes using JAXB – Constantin Jul 14 '15 at 12:52