knorv
knorv

Reputation: 50127

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?

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

Upvotes: 1

Views: 2343

Answers (5)

Thimmayya
Thimmayya

Reputation: 2064

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

Upvotes: 1

Nick Veys
Nick Veys

Reputation: 23939

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

Upvotes: 2

Matt Solnit
Matt Solnit

Reputation: 33544

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

Upvotes: 3

Max A.
Max A.

Reputation: 4882

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.

Upvotes: 0

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

Upvotes: -2

Related Questions