Java XPath Evaluate findNodeAndGetXPath(String qName, String fileName)

Here you can find the source of findNodeAndGetXPath(String qName, String fileName)

Description

find Node And Get X Path

License

Open Source License

Declaration

public static String findNodeAndGetXPath(String qName, String fileName) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2015 UNIT Information Technologies R&D Ltd
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:/*  ww w .  j a  v a 2 s .c om*/
 *     Ferhat Erata - initial API and implementation
 *     H. Emre Kirmizi - initial API and implementation
 *     Serhat Celik - initial API and implementation
 *     U. Anil Ozturk - initial API and implementation
 *******************************************************************************/

import java.io.File;
import java.io.IOException;
import java.util.Stack;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

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

public class Main {
    public static String findNodeAndGetXPath(String qName, String fileName) {
        return getFullXPath(findNode(qName, fileName));
    }

    public static String getFullXPath(Node n) {
        // abort early
        if (null == n)
            return null;

        // declarations
        Node parent = null;
        Stack<Node> hierarchy = new Stack<Node>();
        StringBuffer buffer = new StringBuffer();

        // push element on stack
        hierarchy.push(n);

        switch (n.getNodeType()) {
        case Node.ATTRIBUTE_NODE:
            parent = ((Attr) n).getOwnerElement();
            break;
        case Node.ELEMENT_NODE:
            parent = n.getParentNode();
            break;
        case Node.DOCUMENT_NODE:
            parent = n.getParentNode();
            break;
        default:
            throw new IllegalStateException("Unexpected Node type" + n.getNodeType());
        }

        while (null != parent && parent.getNodeType() != Node.DOCUMENT_NODE) {
            // push on stack
            hierarchy.push(parent);

            // get parent of parent
            parent = parent.getParentNode();
        }

        // construct xpath
        Object obj = null;
        while (!hierarchy.isEmpty() && null != (obj = hierarchy.pop())) {
            Node node = (Node) obj;
            boolean handled = false;

            if (node.getNodeType() == Node.ELEMENT_NODE) {
                Element e = (Element) node;

                // is this the root element?
                if (buffer.length() == 0) {
                    // root element - simply append element name
                    buffer.append(node.getNodeName());
                } else {
                    // child element - append slash and element name
                    buffer.append("/");
                    buffer.append(node.getNodeName());

                    if (node.hasAttributes()) {
                        // see if the element has a name or id attribute
                        if (e.hasAttribute("id")) {
                            // id attribute found - use that
                            buffer.append("[@id='" + e.getAttribute("id") + "']");
                            handled = true;
                        } else if (e.hasAttribute("name") && e.getAttribute("name") != null
                                && !e.getAttribute("name").isEmpty()) {
                            // name attribute found - use that
                            buffer.append("[@name='" + e.getAttribute("name") + "']");
                            handled = true;
                        }
                    }

                    if (!handled) {
                        // no known attribute we could use - get sibling index
                        int prev_siblings = 1;
                        Node prev_sibling = node.getPreviousSibling();
                        while (null != prev_sibling) {
                            if (prev_sibling.getNodeType() == node.getNodeType()) {
                                if (prev_sibling.getNodeName().equalsIgnoreCase(node.getNodeName())) {
                                    prev_siblings++;
                                }
                            }
                            prev_sibling = prev_sibling.getPreviousSibling();
                        }
                        buffer.append("[" + prev_siblings + "]");
                    }
                }
            } else if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
                buffer.append("/@");
                buffer.append(node.getNodeName());
            }
        }
        // return buffer
        return buffer.toString();
    }

    public static Node findNode(String qName, String fileName) {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setValidating(false);
        DocumentBuilder db;
        Document doc;
        try {
            db = dbf.newDocumentBuilder();
            doc = db.parse(new File(fileName));
            Node node = findNode(qName, doc);
            if (node != null) {
                return node;
            }

        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Find the named subnode in a node's sublist.
     * <ul>
     * <li>Ignores comments and processing instructions.
     * <li>Ignores TEXT nodes (likely to exist and contain ignorable whitespace, if not validating.
     * <li>Ignores CDATA nodes and EntityRef nodes.
     * <li>Examines element nodes to find one with the specified name.
     * </ul>
     * 
     * @param name the tag name for the element to find
     * @param node the element node to start searching from
     * @return the Node found
     */
    public static Node findNode(String name, Node node) {
        // get all child nodes
        NodeList list = node.getChildNodes();

        for (int i = 0; i < list.getLength(); i++) {
            // get child node
            Node childNode = list.item(i);

            if (childNode.getNodeType() == Node.ELEMENT_NODE) {
                Element element = (Element) childNode;
                if (element.hasAttributes()) {
                    if (element.hasAttribute("id") && element.getAttribute("id") != null
                            && !element.getAttribute("id").isEmpty() && element.getAttribute("id").equals(name)) {
                        return element;
                    } else if (element.hasAttribute("name") && element.getAttribute("name") != null
                            && !element.getAttribute("name").isEmpty()
                            && element.getAttribute("name").equals(name)) {
                        return element;
                    }
                }
            }
            // visit child node
            Node temp = findNode(name, childNode);
            if (temp != null)
                return temp;
        }
        return null;
    }
}

Related

  1. evalXPathAsString(Object item, String xpath, XPathFactory factory)
  2. evalXPathAsStringList(Object item, String xpath, XPathFactory factory, boolean includeDuplicates)
  3. executeXPath(Document dom, String xpath, QName returnType)
  4. executeXPathExpression(Document document, String expression)
  5. execXPath(org.w3c.dom.Node node, String pattern, QName xPathConstantsType)
  6. getNodesListXpath(final String xPathS, final Node node, final String nsuri, final String pre, final QName returnType)
  7. parseVariable(Node contextNode, String xPathString)
  8. xPath(final Node aNode, final String anXPath, final QName aQName)
  9. xpathEvalElements(String expr, Object e)