使用JAXB输出schema文件
撰写一个JAXB class如下:
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.List;
/**
* @author <a href="mailto:l.weinan@gmail.com">Weinan Li</a>
*/
@XmlRootElement(name = "listType")
public class ListType {
private List<String> values;
@XmlElement
public List<String> getValues() {
return values;
}
public void setValues(List<String> values) {
this.values = values;
}
}
上面的class作为待生成schema file的一个class,下面是生成schema的代码:
import javax.xml.bind.JAXBContext;
import javax.xml.bind.SchemaOutputResolver;
import javax.xml.transform.Result;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.IOException;
/**
* @author <a href="mailto:l.weinan@gmail.com">Weinan Li</a>
*/
public class JavaToXsd {
public static void main(String[] args) throws Exception {
JAXBContext context = JAXBContext.newInstance(ListType.class);
SchemaOutputResolver resolver = new MyResolver();
context.generateSchema(resolver);
}
private static class MyResolver extends SchemaOutputResolver {
public Result createOutput(String namespaceURI, String suggestedFileName) throws IOException {
File file = new File(suggestedFileName);
StreamResult result = new StreamResult(file);
result.setSystemId(file.toURI().toURL().toString());
return result;
}
}
}
在上面的class当中,我们定义了自己的MyResolver
,用来扩展SchemaOutputResolver
:
在上面的class里设置两个断点:
然后执行,可以看到是XmlSchemaGenerator
执行的write(...)
方法当中,调用了resolver:
执行完我们的JavaToXsd
以后,就得到了xsd文件:
$ ls *.xsd
schema1.xsd
$ cat schema1.xsd
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="listType" type="listType"/>$
以上就是java class转xsd的一个流程。