XPath over XML Schema: Examples
Home Downloads
Contents
Sample XSD used in examples
Boilerplate
Examples: 1, 2, 3, 4, 5, 6 (more examples in the download).
Boilerplate
import java.io.File;
import java.io.IOException;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List;
import java.util.Map.Entry;
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlOptions;
import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument;
import xpath.PathElement;
import xpath.XPath;
import xpath.XPathException;
import xpath.schema.Node;
import xpath.schema.SchemaData;

public class XPathExample {

    public static void main(String[] args) {
        Hashtable<String,String> file2prefix = new Hashtable<String,String>();
        file2prefix.put("example.xsd", "ex");
        
        SchemaData schData = loadSchemas(file2prefix);
        if (schData == null) 
            System.out.println("Error loading schemas");
        else {
            example1(schData);
            example2(schData);
            example3(schData);
            example4(schData);
            example5(schData);
            example6(schData);            
        }
    }
    
    public static SchemaData loadSchemas(Hashtable<String,String> file2prefix) {
        SchemaData schData = new SchemaData();
        
        // loading options. Used to instruct loading of line numbers
        // (line numbers are used to find nodes in the schema file)
        XmlOptions options = new XmlOptions();
        options.setLoadLineNumbers();
        options.setLoadLineNumbers(XmlOptions.LOAD_LINE_NUMBERS_END_ELEMENT);

        for (Entry<String,String> xsd: file2prefix.entrySet()) {
            SchemaDocument schema = null;
            try {
                File file = new File(xsd.getKey());
                schema = SchemaDocument.Factory.parse(file, options);
            } catch (XmlException e) {
                System.err.println(e.getMessage());
                return null;
            } catch (IOException e) {
                System.err.println(e.getMessage());
                return null;
            } 
            schData.add(xsd.getValue(), schema);
        }
        
        return schData;
    }
    
    public static void printMatchedNodes(List<PathElement> matched) {
        System.out.println("Matched nodes:");
        for (PathElement pe: matched) {
            System.out.println(pe.toString());
        }
    }
}
    
SourceForge.net Logo Hit Counter