How to generate xsd file using java code?

前端 未结 4 1726
栀梦
栀梦 2021-01-21 22:19

        
            
            

        
4条回答
  •  死守一世寂寞
    2021-01-21 22:41

    Instead of creating your own simple type to represent integers starting with 0, you could leverage the existing xs:nonNegativeInteger type. I'll demonstrate with an example.

    SpThread

    You can use the @XmlSchemaType annotation to specify what type should be generated in the XML schema for a field/property.

    package forum11667335;
    
    import javax.xml.bind.annotation.XmlSchemaType;
    
    public class SpThread {
    
        private int durTime;
    
        @XmlSchemaType(name="nonNegativeInteger")
        public int getDurTime() {
            return durTime;
        }
    
        public void setDurTime(int durTime) {
            this.durTime = durTime;
        }
    
    }
    

    Demo

    You can use the generateSchema method on JAXBContext to generate an XML schema:

    package forum11667335;
    
    import java.io.IOException;
    import javax.xml.bind.*;
    import javax.xml.transform.Result;
    import javax.xml.transform.stream.StreamResult;
    
    public class Demo {
    
        public static void main(String[] args) throws Exception {
            JAXBContext jc = JAXBContext.newInstance(SpThread.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;
                }
    
            });
        }
    
    }
    

    Output

    Below is the XML schema that was generated.

    
    
      
        
          
        
      
    
    

提交回复
热议问题