Example usage for org.w3c.dom Element getParentNode

List of usage examples for org.w3c.dom Element getParentNode

Introduction

In this page you can find the example usage for org.w3c.dom Element getParentNode.

Prototype

public Node getParentNode();

Source Link

Document

The parent of this node.

Usage

From source file:Main.java

/**
 * Returns the XPath to retrieve targetElement from rootElement. rootElement may be null, in this case the XPath starts with and includes
 * the farthest non-null ancestor of targetElement. If rootElement == targetElement, an empty string
 * is returned. /*from  w w  w.ja v a  2  s. c  o  m*/
 * @param includeElementIndex Indicates if the element indices in the form elementName[n] should
 * be included in the XPath. 
 * @param namespacesMap Maps namespace ids to namespace URIs.
 */
public static String getXPath(Element rootElement, Element targetElement, boolean includeElementIndex,
        Map<String, String> namespacesMap) {
    Stack<Element> elementPath = new Stack<Element>();

    // since we need the mapping the other way round, we invert the map
    Map<String, String> namespaceUriToIdMap = new HashMap<String, String>();
    for (Entry<String, String> entry : namespacesMap.entrySet()) {
        namespaceUriToIdMap.put(entry.getValue(), entry.getKey());
    }

    // recursively find all ancestors of targetElement (up to, not including, rootElement) 
    {
        Element currentElement = targetElement;
        while (currentElement != null && currentElement != rootElement) {
            elementPath.push(currentElement);
            Node parent = currentElement.getParentNode();
            if (parent instanceof Element) {
                currentElement = (Element) currentElement.getParentNode();
            } else {
                currentElement = null;
            }
        }
    }

    // construct XPath
    StringBuilder builder = new StringBuilder();
    while (!elementPath.isEmpty()) {
        Element currentElement = elementPath.pop();
        if (builder.length() > 0) {
            // don't include "/" at the beginning
            builder.append("/");
        }

        if (namespacesMap != null) {
            String namespace = currentElement.getNamespaceURI();
            if (namespace != null) {
                namespace = namespaceUriToIdMap.get(namespace);
                builder.append(namespace);
                builder.append(":");
            }
        }
        builder.append(currentElement.getLocalName());
        if (includeElementIndex) {
            int index = getElementIndex(currentElement);
            builder.append("[");
            builder.append(index);
            builder.append("]");
        }
    }
    return builder.toString();
}

From source file:Main.java

public static String resolveNamespacePrefix(String prefix, Element element) {
    String namespace = null;//from  w w w.  j a  v a 2 s  . c o m

    if ("".equals(prefix)) {
        namespace = element.getAttribute("xmlns");
    } else {
        namespace = element.getAttribute("xmlns:" + prefix);
    }
    if (namespace != null && !"".equals(namespace)) {
        return namespace;
    }

    if (element.getParentNode() instanceof Element) {
        return resolveNamespacePrefix(prefix, (Element) element.getParentNode());
    } else {
        throw new RuntimeException("Cannot resolve prefix " + prefix);
    }
}

From source file:Main.java

public static Node createNodeFromPath(Element modelElement, String path) {
    Document document = modelElement.getOwnerDocument();
    StringTokenizer st = new StringTokenizer(path, "/");
    while (st.hasMoreTokens()) {
        String t = st.nextToken();

        if (st.hasMoreTokens()) {
            if (t.equals("..")) {
                modelElement = (Element) modelElement.getParentNode();
            } else {
                Element elm = getFirstChildElement(modelElement, t);
                if (elm == null)
                    modelElement = (Element) modelElement.insertBefore(document.createElement(t),
                            getFirstChildElement(modelElement, t));
                else
                    modelElement = elm;//from w  ww  . j  av  a  2 s.c  o  m
            }
        } else {
            modelElement = (Element) modelElement.insertBefore(document.createElement(t),
                    getFirstChildElement(modelElement, t));
        }
    }

    return modelElement;
}

From source file:com.github.alexfalappa.nbspringboot.projects.initializr.InitializrProjectWizardIterator.java

private static void filterProjectXML(FileObject fo, ZipInputStream str, String name) throws IOException {
    try {/*  ww w  .  j av  a  2  s.  c o m*/
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        FileUtil.copy(str, baos);
        Document doc = XMLUtil.parse(new InputSource(new ByteArrayInputStream(baos.toByteArray())), false,
                false, null, null);
        NodeList nl = doc.getDocumentElement().getElementsByTagName("name");
        if (nl != null) {
            for (int i = 0; i < nl.getLength(); i++) {
                Element el = (Element) nl.item(i);
                if (el.getParentNode() != null && "data".equals(el.getParentNode().getNodeName())) {
                    NodeList nl2 = el.getChildNodes();
                    if (nl2.getLength() > 0) {
                        nl2.item(0).setNodeValue(name);
                    }
                    break;
                }
            }
        }
        try (OutputStream out = fo.getOutputStream()) {
            XMLUtil.write(doc, out, "UTF-8");
        }
    } catch (Exception ex) {
        Exceptions.printStackTrace(ex);
        writeFile(str, fo);
    }

}

From source file:Main.java

public static void edit(Document doc) {
    Element element = doc.getDocumentElement();
    Element element2 = doc.createElement("newname");
    NamedNodeMap attrs = element.getAttributes();
    for (int i = 0; i < attrs.getLength(); i++) {
        Attr attr2 = (Attr) doc.importNode(attrs.item(i), true);
        element2.getAttributes().setNamedItem(attr2);
    }/*from   w  w  w  .j av  a 2s  .  co  m*/
    while (element.hasChildNodes()) {
        element2.appendChild(element.getFirstChild());
    }
    element.getParentNode().replaceChild(element2, element);
}

From source file:com.microsoft.tfs.util.xml.DOMUtils.java

/**
 * Walks the parent chain from the specified element to find the root node.
 *
 * @param descendant// w  w  w .j av a2s . c  o m
 *        The starting point for the parent chain traversal.
 *
 * @return The root node of the document.
 */
public static Element getRootElement(final Element descendant) {
    Element element = descendant;
    while (element.getParentNode() != null && element.getParentNode() instanceof Element) {
        element = (Element) element.getParentNode();
    }
    return element;
}

From source file:Main.java

public static String findPrefixForNamespace(Element elm, String namespace) {
    while (elm != null) {
        NamedNodeMap attributes = elm.getAttributes();
        for (int c = 0; c < attributes.getLength(); c++) {
            if (attributes.item(c).getNodeValue().equals(namespace)
                    && attributes.item(c).getNodeName().startsWith("xmlns:")) {
                return attributes.item(c).getNodeName().substring(6);
            }/*from ww w  . j a  v a 2s .  co  m*/
        }

        if (elm.getParentNode().getNodeType() != Node.ELEMENT_NODE)
            break;

        elm = (Element) elm.getParentNode();
    }

    return null;
}

From source file:Main.java

/**
 * Returns an element parent node with "name" attribute based on a complex
 * key filter (parent.child.child)//  w w w.j  a va  2  s  .  c o m
 * @param xsdDoc
 * @param xsdKey
 * @return
 */
protected static Element getXsdParentComplexKey(Document xsdDoc, String xsdKey) {
    Element tmpRes = null;
    Element element = null;

    String[] splitStr = xsdKey.split("[.]");

    String topParent = splitStr[0];
    String Parent = splitStr[1];
    String Node = splitStr[2];

    try {
        NodeList allNodes = xsdDoc.getElementsByTagName("*");
        for (int i = 0; i < allNodes.getLength(); i++) {
            element = (Element) allNodes.item(i);
            if (element.getAttribute("name").equals(Node)) {
                element = (Element) element.getParentNode();
                while (!((Element) element).hasAttribute("name")) {
                    element = (Element) element.getParentNode();
                }
                if (element.getAttribute("name").equals(Parent)) {
                    Element pElement = (Element) element.getParentNode();
                    while (!((Element) pElement).hasAttribute("name")) {
                        pElement = (Element) pElement.getParentNode();
                    }
                    if (pElement.getAttribute("name").equals(topParent)) {
                        tmpRes = element;
                    }
                }
            }
        }
        return tmpRes;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:Main.java

/**
 * Remove an element using XPath-quotation expressions. Path must not including
 * the context element, path elements can be separated by / or .,
 * and namespace is NOT supported./* w ww  . j a v  a2  s . c o m*/
 * @param context Element to start the search from, cannot be null.
 * @param path XPath-quotation expression, cannot be null.
 * @return the removed element if there are matches, otherwise
 * return null.
 */
public static Element removeElementByPath(Element context, String path) {
    Element cur = context;
    StringTokenizer tokens = new StringTokenizer(path, "/");
    String name = null;
    while (tokens.hasMoreTokens()) {
        name = tokens.nextToken();
        cur = getElementByPath(cur, name);
        if (cur == null) {
            return null;
        }
    }
    if (name != null) {
        Element parent = (Element) cur.getParentNode();
        return removeChildElement(parent, name);
    }
    return null;
}

From source file:DOMUtils.java

/**
 * Given a prefix and a node, return the namespace URI that the prefix
 * has been associated with. This method is useful in resolving the
 * namespace URI of attribute values which are being interpreted as
 * QNames. If prefix is null, this method will return the default
 * namespace./*from w  ww . j  a  v a 2s. co m*/
 *
 * @param context the starting node (looks up recursively from here)
 * @param prefix the prefix to find an xmlns:prefix=uri for
 *
 * @return the namespace URI or null if not found
 */
public static String getNamespaceURIFromPrefix(Node context, String prefix) {
    short nodeType = context.getNodeType();
    Node tempNode = null;

    switch (nodeType) {
    case Node.ATTRIBUTE_NODE: {
        tempNode = ((Attr) context).getOwnerElement();
        break;
    }
    case Node.ELEMENT_NODE: {
        tempNode = context;
        break;
    }
    default: {
        tempNode = context.getParentNode();
        break;
    }
    }

    while (tempNode != null && tempNode.getNodeType() == Node.ELEMENT_NODE) {
        Element tempEl = (Element) tempNode;
        String namespaceURI = (prefix == null) ? getAttribute(tempEl, "xmlns")
                : getAttributeNS(tempEl, NS_URI_XMLNS, prefix);

        if (namespaceURI != null) {
            return namespaceURI;
        } else {
            tempNode = tempEl.getParentNode();
        }
    }

    return null;
}