Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

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

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main {
    public static void main(String[] args) throws Exception {
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setValidating(false);
        domFactory.setNamespaceAware(true);
        domFactory.setIgnoringComments(true);
        domFactory.setIgnoringElementContentWhitespace(true);

        DocumentBuilder builder = domFactory.newDocumentBuilder();
        Document dDoc = builder.parse("C:/data.xsd");

        Node rootNode = dDoc.getElementsByTagName("xs:schema").item(0);
        System.out.println(rootNode.getNodeName());

        XPath xPath1 = XPathFactory.newInstance().newXPath();
        NamespaceContext nsContext = new NamespaceContext() {
            @Override
            public String getNamespaceURI(String prefix) {
                return "http://www.w3.org/2001/XMLSchema";
            }

            @Override
            public String getPrefix(String namespaceURI) {
                return "xs";
            }

            @Override
            public Iterator getPrefixes(String namespaceURI) {
                Set s = new HashSet();
                s.add("xs");
                return s.iterator();
            }
        };
        xPath1.setNamespaceContext((NamespaceContext) nsContext);
        NodeList nList1 = (NodeList) xPath1.evaluate("//xs:schema", dDoc, XPathConstants.NODESET);
        System.out.println(nList1.item(0).getNodeName());

        NodeList nList2 = (NodeList) xPath1.evaluate("//xs:element", rootNode, XPathConstants.NODESET);
        System.out.println(nList2.item(0).getNodeName());
    }
}