Java Code Examples for org.w3c.dom.Element#getParentNode()

The following examples show how to use org.w3c.dom.Element#getParentNode() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CoreDocumentImpl.java    From jdk1.8-source-analysis with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a previously registered element with the specified
 * identifier name, or null if no element is registered.
 *
 * @see #putIdentifier
 * @see #removeIdentifier
 */
public Element getIdentifier(String idName) {

    if (needsSyncData()) {
        synchronizeData();
    }

    if (identifiers == null) {
        return null;
    }
    Element elem = (Element) identifiers.get(idName);
    if (elem != null) {
        // check that the element is in the tree
        Node parent = elem.getParentNode();
        while (parent != null) {
            if (parent == this) {
                return elem;
            }
            parent = parent.getParentNode();
        }
    }
    return null;
}
 
Example 2
Source File: DOMBuilder.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
public void startElement(String namespaceURI, String localName, String qName, Attributes atts) {
    super.startElement(namespaceURI, localName, qName, atts);

    Element e = getCurrentElement();
    locatorTable.storeStartLocation( e, locator );

    // check if this element is an outer-most <jaxb:bindings>
    if( Const.JAXB_NSURI.equals(e.getNamespaceURI())
    &&  "bindings".equals(e.getLocalName()) ) {

        // if this is the root node (meaning that this file is an
        // external binding file) or if the parent is XML Schema element
        // (meaning that this is an "inlined" external binding)
        Node p = e.getParentNode();
        if( p instanceof Document
        ||( p instanceof Element && !e.getNamespaceURI().equals(p.getNamespaceURI()))) {
            outerMostBindings.add(e);   // remember this value
        }
    }
}
 
Example 3
Source File: DOMOutputCapsule.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void write(long[] value, String name, long[] defVal) throws IOException {
    StringBuilder buf = new StringBuilder();
    if (value == null) {
        value = defVal;
    }
    for (long b : value) {
        buf.append(b);
        buf.append(" ");
    }
    //remove last space
    buf.setLength(buf.length() - 1);

    Element el = appendElement(name);
    el.setAttribute("size", String.valueOf(value.length));
    el.setAttribute(dataAttributeName, buf.toString());
    currentElement = (Element) currentElement.getParentNode();
}
 
Example 4
Source File: XmlNode.java    From JsDroidCmd with Mozilla Public License 2.0 6 votes vote down vote up
private void addNamespaces(Namespaces rv, Element element) {
    if (element == null) throw new RuntimeException("element must not be null");
    String myDefaultNamespace = toUri(element.lookupNamespaceURI(null));
    String parentDefaultNamespace = "";
    if (element.getParentNode() != null) {
        parentDefaultNamespace = toUri(element.getParentNode().lookupNamespaceURI(null));
    }
    if (!myDefaultNamespace.equals(parentDefaultNamespace) || !(element.getParentNode() instanceof Element) ) {
        rv.declare(Namespace.create("", myDefaultNamespace));
    }
    NamedNodeMap attributes = element.getAttributes();
    for (int i=0; i<attributes.getLength(); i++) {
        Attr attr = (Attr)attributes.item(i);
        if (attr.getPrefix() != null && attr.getPrefix().equals("xmlns")) {
            rv.declare(Namespace.create(attr.getLocalName(), attr.getValue()));
        }
    }
}
 
Example 5
Source File: DOMBuilder.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public void startElement(String namespaceURI, String localName, String qName, Attributes atts) {
    super.startElement(namespaceURI, localName, qName, atts);

    Element e = getCurrentElement();
    locatorTable.storeStartLocation( e, locator );

    // check if this element is an outer-most <jaxb:bindings>
    if( JAXWSBindingsConstants.JAXWS_BINDINGS.getNamespaceURI().equals(e.getNamespaceURI())
    &&  "bindings".equals(e.getLocalName()) ) {

        // if this is the root node (meaning that this file is an
        // external binding file) or if the parent is XML Schema element
        // (meaning that this is an "inlined" external binding)
        Node p = e.getParentNode();
        if( p instanceof Document) {
            outerMostBindings.add(e);   // remember this value
        }
    }
}
 
Example 6
Source File: DOMUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static String getPrefixRecursive(Element el, String ns) {
    String prefix = getPrefix(el, ns);
    if (prefix == null && el.getParentNode() instanceof Element) {
        prefix = getPrefixRecursive((Element)el.getParentNode(), ns);
    }
    return prefix;
}
 
Example 7
Source File: CanonicalizerBase.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Adds to ns the definitions from the parent elements of el
 * @param el
 * @param ns
 */
protected final void getParentNameSpaces(Element el, NameSpaceSymbTable ns)  {
    Node n1 = el.getParentNode();
    if (n1 == null || Node.ELEMENT_NODE != n1.getNodeType()) {
        return;
    }
    //Obtain all the parents of the element
    List<Element> parents = new ArrayList<Element>();
    Node parent = n1;
    while (parent != null && Node.ELEMENT_NODE == parent.getNodeType()) {
        parents.add((Element)parent);
        parent = parent.getParentNode();
    }
    //Visit them in reverse order.
    ListIterator<Element> it = parents.listIterator(parents.size());
    while (it.hasPrevious()) {
        Element ele = it.previous();
        handleParent(ele, ns);
    }
    parents.clear();
    Attr nsprefix;
    if (((nsprefix = ns.getMappingWithoutRendered(XMLNS)) != null)
            && "".equals(nsprefix.getValue())) {
        ns.addMappingAndRender(
                XMLNS, "", getNullNode(nsprefix.getOwnerDocument()));
    }
}
 
Example 8
Source File: XSDocumentInfo.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Initialize namespace support by collecting all of the namespace
 * declarations in the root's ancestors. This is necessary to
 * support schemas fragments, i.e. schemas embedded in other
 * documents. See,
 *
 * https://jaxp.dev.java.net/issues/show_bug.cgi?id=43
 *
 * Requires the DOM to be created with namespace support enabled.
 */
private void initNamespaceSupport(Element schemaRoot) {
    fNamespaceSupport = new SchemaNamespaceSupport();
    fNamespaceSupport.reset();

    Node parent = schemaRoot.getParentNode();
    while (parent != null && parent.getNodeType() == Node.ELEMENT_NODE
            && !parent.getNodeName().equals("DOCUMENT_NODE"))
    {
        Element eparent = (Element) parent;
        NamedNodeMap map = eparent.getAttributes();
        int length = (map != null) ? map.getLength() : 0;
        for (int i = 0; i < length; i++) {
            Attr attr = (Attr) map.item(i);
            String uri = attr.getNamespaceURI();

            // Check if attribute is an ns decl -- requires ns support
            if (uri != null && uri.equals("http://www.w3.org/2000/xmlns/")) {
                String prefix = attr.getLocalName().intern();
                if (prefix == "xmlns") prefix = "";
                // Declare prefix if not set -- moving upwards
                if (fNamespaceSupport.getURI(prefix) == null) {
                    fNamespaceSupport.declarePrefix(prefix,
                            attr.getValue().intern());
                }
            }
        }
        parent = parent.getParentNode();
    }
}
 
Example 9
Source File: XSDocumentInfo.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Initialize namespace support by collecting all of the namespace
 * declarations in the root's ancestors. This is necessary to
 * support schemas fragments, i.e. schemas embedded in other
 * documents. See,
 *
 * https://jaxp.dev.java.net/issues/show_bug.cgi?id=43
 *
 * Requires the DOM to be created with namespace support enabled.
 */
private void initNamespaceSupport(Element schemaRoot) {
    fNamespaceSupport = new SchemaNamespaceSupport();
    fNamespaceSupport.reset();

    Node parent = schemaRoot.getParentNode();
    while (parent != null && parent.getNodeType() == Node.ELEMENT_NODE
            && !parent.getNodeName().equals("DOCUMENT_NODE"))
    {
        Element eparent = (Element) parent;
        NamedNodeMap map = eparent.getAttributes();
        int length = (map != null) ? map.getLength() : 0;
        for (int i = 0; i < length; i++) {
            Attr attr = (Attr) map.item(i);
            String uri = attr.getNamespaceURI();

            // Check if attribute is an ns decl -- requires ns support
            if (uri != null && uri.equals("http://www.w3.org/2000/xmlns/")) {
                String prefix = attr.getLocalName().intern();
                if (prefix == "xmlns") prefix = "";
                // Declare prefix if not set -- moving upwards
                if (fNamespaceSupport.getURI(prefix) == null) {
                    fNamespaceSupport.declarePrefix(prefix,
                            attr.getValue().intern());
                }
            }
        }
        parent = parent.getParentNode();
    }
}
 
Example 10
Source File: XSDocumentInfo.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Initialize namespace support by collecting all of the namespace
 * declarations in the root's ancestors. This is necessary to
 * support schemas fragments, i.e. schemas embedded in other
 * documents. See,
 *
 * https://jaxp.dev.java.net/issues/show_bug.cgi?id=43
 *
 * Requires the DOM to be created with namespace support enabled.
 */
private void initNamespaceSupport(Element schemaRoot) {
    fNamespaceSupport = new SchemaNamespaceSupport();
    fNamespaceSupport.reset();

    Node parent = schemaRoot.getParentNode();
    while (parent != null && parent.getNodeType() == Node.ELEMENT_NODE
            && !parent.getNodeName().equals("DOCUMENT_NODE"))
    {
        Element eparent = (Element) parent;
        NamedNodeMap map = eparent.getAttributes();
        int length = (map != null) ? map.getLength() : 0;
        for (int i = 0; i < length; i++) {
            Attr attr = (Attr) map.item(i);
            String uri = attr.getNamespaceURI();

            // Check if attribute is an ns decl -- requires ns support
            if (uri != null && uri.equals("http://www.w3.org/2000/xmlns/")) {
                String prefix = attr.getLocalName().intern();
                if (prefix == "xmlns") prefix = "";
                // Declare prefix if not set -- moving upwards
                if (fNamespaceSupport.getURI(prefix) == null) {
                    fNamespaceSupport.declarePrefix(prefix,
                            attr.getValue().intern());
                }
            }
        }
        parent = parent.getParentNode();
    }
}
 
Example 11
Source File: XMLCipher.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Decrypts <code>EncryptedData</code> in a single-part operation.
 *
 * @param element the <code>EncryptedData</code> to decrypt.
 * @return the <code>Node</code> as a result of the decrypt operation.
 * @throws XMLEncryptionException
 */
private Document decryptElement(Element element) throws XMLEncryptionException {
    if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Decrypting element...");
    }

    if (cipherMode != DECRYPT_MODE) {
        log.log(java.util.logging.Level.SEVERE, "XMLCipher unexpectedly not in DECRYPT_MODE...");
    }

    byte[] octets = decryptToByteArray(element);

    if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Decrypted octets:\n" + new String(octets));
    }

    Node sourceParent = element.getParentNode();
    Node decryptedNode = serializer.deserialize(octets, sourceParent);

    // The de-serialiser returns a node whose children we need to take on.
    if (sourceParent != null && Node.DOCUMENT_NODE == sourceParent.getNodeType()) {
        // If this is a content decryption, this may have problems
        contextDocument.removeChild(contextDocument.getDocumentElement());
        contextDocument.appendChild(decryptedNode);
    } else if (sourceParent != null) {
        sourceParent.replaceChild(decryptedNode, element);
    }

    return contextDocument;
}
 
Example 12
Source File: Kyero_3.java    From OpenEstate-IO with Apache License 2.0 5 votes vote down vote up
/**
 * Remove &lt;custom&gt; elements.
 * <p>
 * Kyero 3 does not support &lt;custom&gt; elements in &lt;property&gt; and
 * &lt;agent&gt;.
 * <p>
 * Any occurrence of these elements is removed.
 *
 * @param doc OpenImmo document in version 2.1
 * @throws JaxenException if xpath evaluation failed
 */
protected void removeCustomElements(Document doc) throws JaxenException {
    List nodes = XmlUtils.newXPath(
            "/io:root/io:property/io:custom  | " +
                    "/io:root/io:agent/io:custom",
            doc).selectNodes(doc);
    for (Object item : nodes) {
        Element node = (Element) item;
        Element parentNode = (Element) node.getParentNode();
        parentNode.removeChild(node);
    }
}
 
Example 13
Source File: XMLCipher.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Decrypts <code>EncryptedData</code> in a single-part operation.
 *
 * @param element the <code>EncryptedData</code> to decrypt.
 * @return the <code>Node</code> as a result of the decrypt operation.
 * @throws XMLEncryptionException
 */
private Document decryptElement(Element element) throws XMLEncryptionException {
    if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Decrypting element...");
    }

    if (cipherMode != DECRYPT_MODE) {
        log.log(java.util.logging.Level.SEVERE, "XMLCipher unexpectedly not in DECRYPT_MODE...");
    }

    byte[] octets = decryptToByteArray(element);

    if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Decrypted octets:\n" + new String(octets));
    }

    Node sourceParent = element.getParentNode();
    Node decryptedNode = serializer.deserialize(octets, sourceParent);

    // The de-serialiser returns a node whose children we need to take on.
    if (sourceParent != null && Node.DOCUMENT_NODE == sourceParent.getNodeType()) {
        // If this is a content decryption, this may have problems
        contextDocument.removeChild(contextDocument.getDocumentElement());
        contextDocument.appendChild(decryptedNode);
    } else if (sourceParent != null) {
        sourceParent.replaceChild(decryptedNode, element);
    }

    return contextDocument;
}
 
Example 14
Source File: DOMOutputCapsule.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void write(short[][] value, String name, short[][] defVal) throws IOException {
    if (value == null) return;
    if(Arrays.deepEquals(value, defVal)) return;

    Element el = appendElement(name);
    el.setAttribute("size", String.valueOf(value.length));

    for (int i=0; i<value.length; i++) {
            short[] array = value[i];
            write(array, "array_"+i, defVal==null?null:defVal[i]);
    }
    currentElement = (Element) el.getParentNode();
}
 
Example 15
Source File: OpenImmo_1_2_1.java    From OpenEstate-IO with Apache License 2.0 5 votes vote down vote up
/**
 * Remove &lt;objektart_zusatz&gt; elements.
 * <p>
 * OpenImmo 1.2.0 does not support &lt;objektart_zusatz&gt; elements.
 *
 * @param doc OpenImmo document in version 1.2.1
 * @throws JaxenException if xpath evaluation failed
 */
protected void removeObjektartZusatzElements(Document doc) throws JaxenException {
    List nodes = XmlUtils.newXPath(
            "/io:openimmo/io:anbieter/io:immobilie/io:objektkategorie/io:objektart/io:objektart_zusatz",
            doc).selectNodes(doc);
    for (Object item : nodes) {
        Element node = (Element) item;
        Element parentNode = (Element) node.getParentNode();
        parentNode.removeChild(node);
    }
}
 
Example 16
Source File: DOMOutputCapsule.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void write(String[][] value, String name, String[][] defVal) throws IOException {
    if (value == null) return;
    if(Arrays.deepEquals(value, defVal)) return;

    Element el = appendElement(name);
    el.setAttribute("size", String.valueOf(value.length));

    for (int i=0; i<value.length; i++) {
            String[] array = value[i];
            write(array, "array_"+i, defVal==null?null:defVal[i]);
    }
    currentElement = (Element) el.getParentNode();
}
 
Example 17
Source File: OpenImmo_1_2_2.java    From OpenEstate-IO with Apache License 2.0 5 votes vote down vote up
/**
 * Downgrade &lt;energiepass&gt; elements to OpenImmo 1.2.1.
 * <p>
 * The &lt;epart&gt; child element of the &lt;energiepass&gt; element is
 * renamed to &lt;art&gt; in version 1.2.1.
 *
 * @param doc OpenImmo document in version 1.2.2
 * @throws JaxenException if xpath evaluation failed
 */
protected void downgradeEnergiepassElements(Document doc) throws JaxenException {
    List nodes = XmlUtils.newXPath(
            "/io:openimmo/io:anbieter/io:immobilie/io:zustand_angaben/io:energiepass/io:epart",
            doc).selectNodes(doc);
    for (Object item : nodes) {
        Element node = (Element) item;
        Element parentNode = (Element) node.getParentNode();

        Element newNode = doc.createElementNS(StringUtils.EMPTY, "art");
        newNode.setTextContent(node.getTextContent());

        parentNode.replaceChild(newNode, node);
    }
}
 
Example 18
Source File: UserController.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Checking conflicting namespaces and use renameNode and normalizeDocument.
 * @see <a href="content/accountInfo.xml">accountInfo.xml</a>
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testAddUser() throws Exception {
    String resultFile = USER_DIR + "accountRole.out";
    String xmlFile = XML_DIR + "accountInfo.xml";

    // Copy schema for outputfile
    Files.copy(Paths.get(XML_DIR, "accountInfo.xsd"),
            Paths.get(USER_DIR, "accountInfo.xsd"),
            StandardCopyOption.REPLACE_EXISTING);
    MyErrorHandler eh = new MyErrorHandler();
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI);
    dbf.setNamespaceAware(true);
    dbf.setValidating(true);

    DocumentBuilder docBuilder = dbf.newDocumentBuilder();
    docBuilder.setErrorHandler(eh);

    Document document = docBuilder.parse(xmlFile);
    Element sell = (Element) document.getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "Sell").item(0);
    Element role = (Element) sell.getParentNode();

    Element buy = (Element) document.renameNode(sell, PORTAL_ACCOUNT_NS, "acc:Buy");
    role.appendChild(buy);

    DOMImplementationLS impl
            = (DOMImplementationLS) DOMImplementationRegistry
                    .newInstance().getDOMImplementation("LS");
    LSSerializer writer = impl.createLSSerializer();


    try(FileOutputStream output = new FileOutputStream(resultFile)) {
        MyDOMOutput mydomoutput = new MyDOMOutput();
        mydomoutput.setByteStream(output);
        writer.write(document, mydomoutput);
    }

    docBuilder.parse(resultFile);
    assertFalse(eh.isAnyError());
}
 
Example 19
Source File: MenuEntryOperationsImpl.java    From gvnix with GNU General Public License v3.0 4 votes vote down vote up
/** {@inheritDoc} */
public void moveBefore(JavaSymbolName pageId, JavaSymbolName beforeId) {
    Document document = getMenuDocument();

    // make the root element of the menu the one with the menu identifier
    // allowing for different decorations of menu
    Element rootElement = XmlUtils.findFirstElement(ID_MENU_EXP,
            (Element) document.getFirstChild());

    if (!rootElement.getNodeName().equals(GVNIX_MENU)) {
        throw new IllegalArgumentException(INVALID_XML);
    }

    // check for existence of menu category by looking for the identifier
    // provided
    Element pageElement = XmlUtils
            .findFirstElement(
                    ID_EXP.concat(pageId.getSymbolName()).concat("']"),
                    rootElement);

    // exit if menu entry doesn't exist
    Validate.notNull(pageElement, PAGE.concat(pageId.getSymbolName())
            .concat(NOT_FOUND));

    Element beforeElement = XmlUtils.findFirstElement(
            ID_EXP.concat(beforeId.getSymbolName()).concat("']"),
            rootElement);

    // exit if menu entry doesn't exist
    Validate.notNull(beforeElement, PAGE.concat(beforeId.getSymbolName())
            .concat(NOT_FOUND));

    // page parent element where remove menu entry element
    Element pageParentEl = (Element) pageElement.getParentNode();
    pageParentEl.removeChild(pageElement);

    // before parent element where execute insert before
    Element beforeParentEl = (Element) beforeElement.getParentNode();
    beforeParentEl.insertBefore(pageElement, beforeElement);

    writeXMLConfigIfNeeded(document);
}
 
Example 20
Source File: BPELPlanContext.java    From container with Apache License 2.0 3 votes vote down vote up
/**
 * Appends the given node the the main sequence of the buildPlan this context belongs to
 *
 * @param node a XML DOM Node
 * @return true if adding the node to the main sequence was successfull
 */
public boolean appendToInitSequence(final Node node) {
    final Node importedNode = importNode(node);

    final Element flowElement = this.templateBuildPlan.getBuildPlan().getBpelMainFlowElement();

    final Node mainSequenceNode = flowElement.getParentNode();

    mainSequenceNode.insertBefore(importedNode, flowElement);

    return true;
}