如何在java中使用XML Data创建XSD文件

问题描述 投票:-3回答:4

我有像这样的XML数据

<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>

如何使用java创建xsd文件?以及如何为上面的xml数据创建java类(pojo / bean)?我试过这种方式

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 
    }
  }); 
}

但仍然没有进入XSD根元素谢谢

java xml parsing xsd
4个回答
1
投票

如果你正在使用eclipse你可以做以下。

  • 在任何项目中创建XML文件。
  • 右键单击XML文件,单击生成模式。
  • 给它起个名字

尝试从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>

然后右键单击xsd并选择generate java classes


1
投票

您的起点应该是XSD文件。您可以使用在线XSD生成器从XML构建一个:http://www.freeformatter.com/xsd-generator.html

您还可以使用像Trang http://www.thaiopensource.com/relaxng/trang.html这样的工具

或者,如果您想构建自己的XSD生成器,请查看此链接Generate XSD programmatically in java

最后,这里有一些可能有帮助的JAXB示例......

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;
  }
}

你可能需要下载一些依赖jar来使这个工作:https://jaxb.java.net/2.2.11/


0
投票

我试过这种方式公共类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}});但仍然没有进入XSD根元素


© www.soinside.com 2019 - 2024. All rights reserved.