Johannes K. Lehnert
Johannes K. Lehnert

Reputation: 949

Convert XSD to tree structure with Java

I want to generate documentation for XML schemas.

My goal is to analyze the xsd file and to display it as a tree structure (with all complex / anonymous types resolved). Furthermore I need to annotate all items in that tree with their cardinality (as defined by the schema).

The following small example might help to clarify my problem.

a) the xsd file:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="client" type="clientType" />
    <xs:complexType name="clientType">
        <xs:sequence minOccurs="1" maxOccurs="1">
            <xs:element name="first_name"/>
            <xs:element name="last_name"/>
            <xs:element name="address" type="addressType" 
                        minOccurs="1" maxOccurs="unbounded"/>
        </xs:sequence>
    </xs:complexType>
    <xs:complexType name="addressType">
        <xs:sequence>
            <xs:element name="street"/>
            <xs:element name="number" minOccurs="0" maxOccurs="1"/>
            <xs:element name="city"/>
            <xs:element name="zipcode"/>
        </xs:sequence>
    </xs:complexType>
</xs:schema>

b) Output I'd like to see:

client [1]
  first_name [1]
  last_name [1]
  address [1..n]
    street [1]
    number [0..1]
    city [1]
    zipcode [1]

Does anybody know a java based solution for this problem? Preferably based on Eclipse Schema Infoset, but I'm happy to use other libraries as well.

Upvotes: 5

Views: 3181

Answers (3)

Michael Wein
Michael Wein

Reputation: 33

Although not having a proper solution I would propose the following: use a tool that is capable of generating a sample XML instance based on the XSD, e.g. eclipse IDE (as it is open source it should be possible to extract the relevant code and use it within a standalone solution). This XML should be very close to the tree structure you are requiring. Then, parse the XSD and annotate the elements in the generated XML structure with the cardinalities.

Upvotes: 0

jiggy
jiggy

Reputation: 3826

XSOM can normalize an XSD into a comprehensible data structure that you can loop over and print out.

Upvotes: 1

Chris R
Chris R

Reputation: 2564

Given that XSD schema are also XML you could process this as XML giving you many options for how to do this.

My preference would be to use an XSLT stylesheet with templates to match the element and complex type elements to get the output list, and further templates to match the minOccurs and maxOccurs attributes to get your cardinality.

Examples of stylsheets to do this are probably available online already.

Upvotes: 0

Related Questions