开发者

Getting an object representation of an .XSD file in Java

What is the easiest way to obtain a statically typed representation of an XML schema (.XSD) in Java?

M开发者_C百科ore specifically I want to be able to programatically traverse all defined simpleType:s and complexType:s in the XSD, obtain defined elements and their types, etc.

Something along the lines of:

for (XsdComplexType complexType : document.getDefinedComplexTypes()) {
  ..
}

Please note: I'm talking about an object representation of the .XSD document. I'm not looking for xjc style generation of Java classes from an XML schema.

One approach would be to simply apply standard XML reading tools to the .XSD file, but I'd assume there are open-source libraries around that could help me tackle the problem. As seen in the pseudo-code above I'd like a statically typed representation of the XSD document.


Have you looked at Apache XmlSchema? I've never used it, but it seems like a good fit.


Check out the Castor XML library's Schema class. And the SchemaReader to load it up. It should be exactly what you're looking for.

Contains methods like:


 public java.util.Enumeration getComplexTypes()
    Returns:
        an Enumeration of all top-level ComplexType declarations


Try org.apache.ws.jaxme.generator.sg.impl.JAXBSchemaReader. Here's a sample code snippet which may work:

org.apache.ws.jaxme.generator.sg.SchemaSG schema = JaxbSchemaReader.parse(schema);
org.apache.ws.jaxme.generator.sg.TypeSG types = schema.getTypes();
for (TypeSG type : types) {
    if (type.getComplexTypeSG() != null) {
           //do something here
    }
 }


While I agree with and want to second the other two (at the moment) answers that proposed using a standard tool such as dom4j or jdom, I'd like to posit an off-the-wall suggestion. You can use JiBX or another XML data binding tool to produce Java objects of your liking directly from the schema XML.

Or you could just use a standard DOM parser.


Why not just read it in as a DOM Document and then do whatever you want to do with it?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜