How to generate xsd file using java code?

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

        
            
            

        
相关标签:
4条回答
  • 2021-01-21 22:38

    I recommend you JAXB to any XML jobs you do. But normally XSD files are generated manually and then XML files are generated programatically using the XSD files. What are you trying to develop?

    0 讨论(0)
  • 2021-01-21 22:40

    You can use Java2Schema tool for generating schema from java classes, and also you can try JaxB 2.0

    0 讨论(0)
  • 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.

    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">
      <xs:complexType name="spThread">
        <xs:sequence>
          <xs:element name="durTime" type="xs:nonNegativeInteger"/>
        </xs:sequence>
      </xs:complexType>
    </xs:schema>
    
    0 讨论(0)
  • 2021-01-21 22:53

    You can use any XML-handling API to achieve this. JDOM is one of them. If you'd like an API specific to building XML Schemas which you then serialize into XML, you might want to check out Eclipse MDT API.

    0 讨论(0)
提交回复
热议问题