// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;

import javax.xml.namespace.NamespaceContext;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class XMIParse {
    public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(new InputSource(new FileReader("/work/xmi.xml")));
        XPath xpath = XPathFactory.newInstance().newXPath();
        xpath.setNamespaceContext(new NamespaceContext() {
            public String getNamespaceURI(String prefix) {
                if(prefix.equals("UML")) {
                    return "http://org.omg/UML/1.3";
                } else {
                    return null;
                }
            }
            public String getPrefix(String namespace) {
                if(namespace.equals("http://org.omg/UML/1.3")) {
                    return "UML";
                } else {
                    return null;
                }
            }
            public Iterator getPrefixes(String namespace) {
                return null;
            }
        });
        NodeList clzes = (NodeList)xpath.evaluate("//XMI/XMI.content/UML:Model/UML:Namespace.ownedElement/UML:Class", doc.getDocumentElement(), XPathConstants.NODESET);
        for(int i = 0; i < clzes.getLength(); i++) {
            Node clz = clzes.item(i);
            System.out.println(clz.getAttributes().getNamedItem("visibility") + " " + clz.getAttributes().getNamedItem("name"));
        }
    }
}
