Friday, March 23, 2012

Parsing complex Xsd file with Java code.

This one nearly 4+ year old code. Now Team is using apache xerces XSModel.
However this code is there for sanity check. Still this works fine.
(You need xsom.jar + relaxngDatatype.jar file. Google it. You will find the jars.)


public class XsdReader {
public static void main (String args[])
{
XsdReader rr = new XsdReader();
rr.parseSchema();
}

public void parseSchema()
{
File file = new File("D:\\tmp\\books.xsd");
try {
XSOMParser parser = new XSOMParser();
parser.parse(file);
XSSchemaSet sset = parser.getResult();
XSSchema mys = sset.getSchema(1);
Iterator itr = sset.iterateSchema();
while( itr.hasNext() ) {
XSSchema s = (XSSchema)itr.next();
System.out.println("Target namespace: "+s.getTargetNamespace());
XSComplexType ct = mys.getComplexType("books");
int ctr=0;
if ( ct != null){
Collection c = ct.getAttributeUses();
Iterator i = c.iterator();while(i.hasNext()){
XSAttributeDecl attributeDecl = i.next().getDecl();

System.out.print("ctr="+ctr++ +"name:"+ attributeDecl.getName());
System.out.print(" type: "+attributeDecl.getType());
System.out.println("");
}
}
Iterator jtr = s.iterateElementDecls();
while( jtr.hasNext() ) {
XSElementDecl e = (XSElementDecl)jtr.next();

System.out.print( e.getName() );
if( e.isAbstract() )
System.out.print(" (abstract)");
System.out.println();
}
}
}
catch (Exception exp) {
exp.printStackTrace(System.out);
}
}
}

1 comment:

Unknown said...

i have an xsd file. I tried runing the program but it wouldnt go inside the iterator as ct variable is showing as null