Java Code Examples for org.w3c.dom.Attr#getNodeName()

The following examples show how to use org.w3c.dom.Attr#getNodeName() . 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: C14nHelper.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * This method throws an exception if the Attribute value contains
 * a relative URI.
 *
 * @param attr
 * @throws CanonicalizationException
 */
public static void assertNotRelativeNS(Attr attr) throws CanonicalizationException {
    if (attr == null) {
        return;
    }

    String nodeAttrName = attr.getNodeName();
    boolean definesDefaultNS = nodeAttrName.equals("xmlns");
    boolean definesNonDefaultNS = nodeAttrName.startsWith("xmlns:");

    if ((definesDefaultNS || definesNonDefaultNS) && namespaceIsRelative(attr)) {
        String parentName = attr.getOwnerElement().getTagName();
        String attrValue = attr.getValue();
        Object exArgs[] = { parentName, nodeAttrName, attrValue };

        throw new CanonicalizationException(
            "c14n.Canonicalizer.RelativeNamespace", exArgs
        );
    }
}
 
Example 2
Source File: SetAttributeNode.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void test2() {
    String name = "attr";
    String oldValue = "old value";
    String newValue = "new value";
    Attr retAttr;

    IIOMetadataNode parent = new IIOMetadataNode("parent");
    MyAttrNode attrNode1 = new MyAttrNode(name, oldValue);
    MyAttrNode attrNode2 = new MyAttrNode(name, newValue);

    retAttr = parent.setAttributeNode(attrNode1);
    retAttr = parent.setAttributeNode(attrNode2);

    String actName = retAttr.getNodeName();
    String actValue = retAttr.getValue();

    if (!actName.equals(name) || !actValue.equals(oldValue)) {
        throw new RuntimeException("Test 2 failed: Invalid attribute " +
                                   "returned: " +
                                   "(name: " + actName +
                                   ", value: " + actValue + ")");
    }
}
 
Example 3
Source File: C14nHelper.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * This method throws an exception if the Attribute value contains
 * a relative URI.
 *
 * @param attr
 * @throws CanonicalizationException
 */
public static void assertNotRelativeNS(Attr attr) throws CanonicalizationException {
    if (attr == null) {
        return;
    }

    String nodeAttrName = attr.getNodeName();
    boolean definesDefaultNS = nodeAttrName.equals("xmlns");
    boolean definesNonDefaultNS = nodeAttrName.startsWith("xmlns:");

    if ((definesDefaultNS || definesNonDefaultNS) && namespaceIsRelative(attr)) {
        String parentName = attr.getOwnerElement().getTagName();
        String attrValue = attr.getValue();
        Object exArgs[] = { parentName, nodeAttrName, attrValue };

        throw new CanonicalizationException(
            "c14n.Canonicalizer.RelativeNamespace", exArgs
        );
    }
}
 
Example 4
Source File: SetAttributeNode.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
public static void test2() {
    String name = "attr";
    String oldValue = "old value";
    String newValue = "new value";
    Attr retAttr;

    IIOMetadataNode parent = new IIOMetadataNode("parent");
    MyAttrNode attrNode1 = new MyAttrNode(name, oldValue);
    MyAttrNode attrNode2 = new MyAttrNode(name, newValue);

    retAttr = parent.setAttributeNode(attrNode1);
    retAttr = parent.setAttributeNode(attrNode2);

    String actName = retAttr.getNodeName();
    String actValue = retAttr.getValue();

    if (!actName.equals(name) || !actValue.equals(oldValue)) {
        throw new RuntimeException("Test 2 failed: Invalid attribute " +
                                   "returned: " +
                                   "(name: " + actName +
                                   ", value: " + actValue + ")");
    }
}
 
Example 5
Source File: SetAttributeNode.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
public static void test2() {
    String name = "attr";
    String oldValue = "old value";
    String newValue = "new value";
    Attr retAttr;

    IIOMetadataNode parent = new IIOMetadataNode("parent");
    MyAttrNode attrNode1 = new MyAttrNode(name, oldValue);
    MyAttrNode attrNode2 = new MyAttrNode(name, newValue);

    retAttr = parent.setAttributeNode(attrNode1);
    retAttr = parent.setAttributeNode(attrNode2);

    String actName = retAttr.getNodeName();
    String actValue = retAttr.getValue();

    if (!actName.equals(name) || !actValue.equals(oldValue)) {
        throw new RuntimeException("Test 2 failed: Invalid attribute " +
                                   "returned: " +
                                   "(name: " + actName +
                                   ", value: " + actValue + ")");
    }
}
 
Example 6
Source File: DOMStreamReader.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * If the given attribute is a namespace declaration for the given namespace URI,
 * return its prefix. Otherwise null.
 */
private static String getPrefixForAttr(Attr attr, String nsUri) {
    String attrName = attr.getNodeName();
    if (!attrName.startsWith("xmlns:") && !attrName.equals("xmlns"))
        return null;    // not nsdecl

    if(attr.getValue().equals(nsUri)) {
        if(attrName.equals("xmlns"))
            return "";
        String localName = attr.getLocalName();
        return (localName != null) ? localName :
            QName.valueOf(attrName).getLocalPart();
    }

    return null;
}
 
Example 7
Source File: SetAttributeNode.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void test2() {
    String name = "attr";
    String oldValue = "old value";
    String newValue = "new value";
    Attr retAttr;

    IIOMetadataNode parent = new IIOMetadataNode("parent");
    MyAttrNode attrNode1 = new MyAttrNode(name, oldValue);
    MyAttrNode attrNode2 = new MyAttrNode(name, newValue);

    retAttr = parent.setAttributeNode(attrNode1);
    retAttr = parent.setAttributeNode(attrNode2);

    String actName = retAttr.getNodeName();
    String actValue = retAttr.getValue();

    if (!actName.equals(name) || !actValue.equals(oldValue)) {
        throw new RuntimeException("Test 2 failed: Invalid attribute " +
                                   "returned: " +
                                   "(name: " + actName +
                                   ", value: " + actValue + ")");
    }
}
 
Example 8
Source File: SetAttributeNode.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
public static void test2() {
    String name = "attr";
    String oldValue = "old value";
    String newValue = "new value";
    Attr retAttr;

    IIOMetadataNode parent = new IIOMetadataNode("parent");
    MyAttrNode attrNode1 = new MyAttrNode(name, oldValue);
    MyAttrNode attrNode2 = new MyAttrNode(name, newValue);

    retAttr = parent.setAttributeNode(attrNode1);
    retAttr = parent.setAttributeNode(attrNode2);

    String actName = retAttr.getNodeName();
    String actValue = retAttr.getValue();

    if (!actName.equals(name) || !actValue.equals(oldValue)) {
        throw new RuntimeException("Test 2 failed: Invalid attribute " +
                                   "returned: " +
                                   "(name: " + actName +
                                   ", value: " + actValue + ")");
    }
}
 
Example 9
Source File: SetAttributeNode.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
public static void test2() {
    String name = "attr";
    String oldValue = "old value";
    String newValue = "new value";
    Attr retAttr;

    IIOMetadataNode parent = new IIOMetadataNode("parent");
    MyAttrNode attrNode1 = new MyAttrNode(name, oldValue);
    MyAttrNode attrNode2 = new MyAttrNode(name, newValue);

    retAttr = parent.setAttributeNode(attrNode1);
    retAttr = parent.setAttributeNode(attrNode2);

    String actName = retAttr.getNodeName();
    String actValue = retAttr.getValue();

    if (!actName.equals(name) || !actValue.equals(oldValue)) {
        throw new RuntimeException("Test 2 failed: Invalid attribute " +
                                   "returned: " +
                                   "(name: " + actName +
                                   ", value: " + actValue + ")");
    }
}
 
Example 10
Source File: W3CNamespaceContext.java    From cxf with Apache License 2.0 6 votes vote down vote up
private String getPrefix(Element e, String uri) {
    NamedNodeMap attributes = e.getAttributes();
    if (attributes != null) {
        for (int i = 0; i < attributes.getLength(); i++) {
            Attr a = (Attr)attributes.item(i);

            String val = a.getValue();
            if (val != null && val.equals(uri)) {
                String name = a.getNodeName();
                if ("xmlns".equals(name)) {
                    return "";
                }
                return name.substring(6);
            }
        }
    }

    Node n = e.getParentNode();
    if (n instanceof Element && n != e) {
        return getPrefix((Element)n, uri);
    }

    return null;
}
 
Example 11
Source File: DOMStreamReader.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
/**
 * If the given attribute is a namespace declaration for the given namespace URI,
 * return its prefix. Otherwise null.
 */
private static String getPrefixForAttr(Attr attr, String nsUri) {
    String attrName = attr.getNodeName();
    if (!attrName.startsWith("xmlns:") && !attrName.equals("xmlns"))
        return null;    // not nsdecl

    if(attr.getValue().equals(nsUri)) {
        if(attrName.equals("xmlns"))
            return "";
        String localName = attr.getLocalName();
        return (localName != null) ? localName :
            QName.valueOf(attrName).getLocalPart();
    }

    return null;
}
 
Example 12
Source File: DOMStreamReader.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Called when the current node is {@link Element} to look at attribute list
 * (which contains both ns decl and attributes in DOM) and split them
 * to attributes-proper and namespace decls.
 */
protected void splitAttributes() {
    // Clear attribute and namespace lists
    _currentAttributes.clear();

    Scope scope = allocateScope();

    _namedNodeMap = _current.getAttributes();
    if (_namedNodeMap != null) {
        final int n = _namedNodeMap.getLength();
        for (int i = 0; i < n; i++) {
            final Attr attr = (Attr) _namedNodeMap.item(i);
            final String attrName = attr.getNodeName();
            if (attrName.startsWith("xmlns:") || attrName.equals("xmlns")) {     // NS decl?
                scope.currentNamespaces.add(attr);
            }
            else {
                _currentAttributes.add(attr);
            }
        }
    }

    // verify that all the namespaces used in element and attributes are indeed available
    ensureNs(_current);
    for( int i=_currentAttributes.size()-1; i>=0; i-- ) {
        Attr a = _currentAttributes.get(i);
        if(fixNull(a.getNamespaceURI()).length()>0)
            ensureNs(a);    // no need to declare "" for attributes in the default namespace
    }
}
 
Example 13
Source File: DOMStreamReader.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Called when the current node is {@link Element} to look at attribute list
 * (which contains both ns decl and attributes in DOM) and split them
 * to attributes-proper and namespace decls.
 */
protected void splitAttributes() {
    // Clear attribute and namespace lists
    _currentAttributes.clear();

    Scope scope = allocateScope();

    _namedNodeMap = _current.getAttributes();
    if (_namedNodeMap != null) {
        final int n = _namedNodeMap.getLength();
        for (int i = 0; i < n; i++) {
            final Attr attr = (Attr) _namedNodeMap.item(i);
            final String attrName = attr.getNodeName();
            if (attrName.startsWith("xmlns:") || attrName.equals("xmlns")) {     // NS decl?
                scope.currentNamespaces.add(attr);
            }
            else {
                _currentAttributes.add(attr);
            }
        }
    }

    // verify that all the namespaces used in element and attributes are indeed available
    ensureNs(_current);
    for( int i=_currentAttributes.size()-1; i>=0; i-- ) {
        Attr a = _currentAttributes.get(i);
        if(fixNull(a.getNamespaceURI()).length()>0)
            ensureNs(a);    // no need to declare "" for attributes in the default namespace
    }
}
 
Example 14
Source File: DOMStreamReader.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Called when the current node is {@link Element} to look at attribute list
 * (which contains both ns decl and attributes in DOM) and split them
 * to attributes-proper and namespace decls.
 */
protected void splitAttributes() {
    // Clear attribute and namespace lists
    _currentAttributes.clear();

    Scope scope = allocateScope();

    _namedNodeMap = _current.getAttributes();
    if (_namedNodeMap != null) {
        final int n = _namedNodeMap.getLength();
        for (int i = 0; i < n; i++) {
            final Attr attr = (Attr) _namedNodeMap.item(i);
            final String attrName = attr.getNodeName();
            if (attrName.startsWith("xmlns:") || attrName.equals("xmlns")) {     // NS decl?
                scope.currentNamespaces.add(attr);
            }
            else {
                _currentAttributes.add(attr);
            }
        }
    }

    // verify that all the namespaces used in element and attributes are indeed available
    ensureNs(_current);
    for( int i=_currentAttributes.size()-1; i>=0; i-- ) {
        Attr a = _currentAttributes.get(i);
        if(fixNull(a.getNamespaceURI()).length()>0)
            ensureNs(a);    // no need to declare "" for attributes in the default namespace
    }
}
 
Example 15
Source File: DOMUtil.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Copies the source tree into the specified place in a destination
 * tree. The source node and its children are appended as children
 * of the destination node.
 * <p>
 * <em>Note:</em> This is an iterative implementation.
 */
public static void copyInto(Node src, Node dest) throws DOMException {

    // get node factory
    Document factory = dest.getOwnerDocument();
    boolean domimpl = factory instanceof DocumentImpl;

    // placement variables
    Node start  = src;
    Node parent = src;
    Node place  = src;

    // traverse source tree
    while (place != null) {

        // copy this node
        Node node = null;
        int  type = place.getNodeType();
        switch (type) {
        case Node.CDATA_SECTION_NODE: {
            node = factory.createCDATASection(place.getNodeValue());
            break;
        }
        case Node.COMMENT_NODE: {
            node = factory.createComment(place.getNodeValue());
            break;
        }
        case Node.ELEMENT_NODE: {
            Element element = factory.createElement(place.getNodeName());
            node = element;
            NamedNodeMap attrs  = place.getAttributes();
            int attrCount = attrs.getLength();
            for (int i = 0; i < attrCount; i++) {
                Attr attr = (Attr)attrs.item(i);
                String attrName = attr.getNodeName();
                String attrValue = attr.getNodeValue();
                element.setAttribute(attrName, attrValue);
                if (domimpl && !attr.getSpecified()) {
                    ((AttrImpl)element.getAttributeNode(attrName)).setSpecified(false);
                }
            }
            break;
        }
        case Node.ENTITY_REFERENCE_NODE: {
            node = factory.createEntityReference(place.getNodeName());
            break;
        }
        case Node.PROCESSING_INSTRUCTION_NODE: {
            node = factory.createProcessingInstruction(place.getNodeName(),
                    place.getNodeValue());
            break;
        }
        case Node.TEXT_NODE: {
            node = factory.createTextNode(place.getNodeValue());
            break;
        }
        default: {
            throw new IllegalArgumentException("can't copy node type, "+
                    type+" ("+
                    place.getNodeName()+')');
        }
        }
        dest.appendChild(node);

        // iterate over children
        if (place.hasChildNodes()) {
            parent = place;
            place  = place.getFirstChild();
            dest   = node;
        }

        // advance
        else {
            place = place.getNextSibling();
            while (place == null && parent != start) {
                place  = parent.getNextSibling();
                parent = parent.getParentNode();
                dest   = dest.getParentNode();
            }
        }

    }

}
 
Example 16
Source File: DOMUtil.java    From JDKSourceCode1.8 with MIT License 4 votes vote down vote up
/**
 * Copies the source tree into the specified place in a destination
 * tree. The source node and its children are appended as children
 * of the destination node.
 * <p>
 * <em>Note:</em> This is an iterative implementation.
 */
public static void copyInto(Node src, Node dest) throws DOMException {

    // get node factory
    Document factory = dest.getOwnerDocument();
    boolean domimpl = factory instanceof DocumentImpl;

    // placement variables
    Node start  = src;
    Node parent = src;
    Node place  = src;

    // traverse source tree
    while (place != null) {

        // copy this node
        Node node = null;
        int  type = place.getNodeType();
        switch (type) {
        case Node.CDATA_SECTION_NODE: {
            node = factory.createCDATASection(place.getNodeValue());
            break;
        }
        case Node.COMMENT_NODE: {
            node = factory.createComment(place.getNodeValue());
            break;
        }
        case Node.ELEMENT_NODE: {
            Element element = factory.createElement(place.getNodeName());
            node = element;
            NamedNodeMap attrs  = place.getAttributes();
            int attrCount = attrs.getLength();
            for (int i = 0; i < attrCount; i++) {
                Attr attr = (Attr)attrs.item(i);
                String attrName = attr.getNodeName();
                String attrValue = attr.getNodeValue();
                element.setAttribute(attrName, attrValue);
                if (domimpl && !attr.getSpecified()) {
                    ((AttrImpl)element.getAttributeNode(attrName)).setSpecified(false);
                }
            }
            break;
        }
        case Node.ENTITY_REFERENCE_NODE: {
            node = factory.createEntityReference(place.getNodeName());
            break;
        }
        case Node.PROCESSING_INSTRUCTION_NODE: {
            node = factory.createProcessingInstruction(place.getNodeName(),
                    place.getNodeValue());
            break;
        }
        case Node.TEXT_NODE: {
            node = factory.createTextNode(place.getNodeValue());
            break;
        }
        default: {
            throw new IllegalArgumentException("can't copy node type, "+
                    type+" ("+
                    place.getNodeName()+')');
        }
        }
        dest.appendChild(node);

        // iterate over children
        if (place.hasChildNodes()) {
            parent = place;
            place  = place.getFirstChild();
            dest   = node;
        }

        // advance
        else {
            place = place.getNextSibling();
            while (place == null && parent != start) {
                place  = parent.getNextSibling();
                parent = parent.getParentNode();
                dest   = dest.getParentNode();
            }
        }

    }

}
 
Example 17
Source File: DOMUtil.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Copies the source tree into the specified place in a destination
 * tree. The source node and its children are appended as children
 * of the destination node.
 * <p>
 * <em>Note:</em> This is an iterative implementation.
 */
public static void copyInto(Node src, Node dest) throws DOMException {

    // get node factory
    Document factory = dest.getOwnerDocument();
    boolean domimpl = factory instanceof DocumentImpl;

    // placement variables
    Node start  = src;
    Node parent = src;
    Node place  = src;

    // traverse source tree
    while (place != null) {

        // copy this node
        Node node = null;
        int  type = place.getNodeType();
        switch (type) {
        case Node.CDATA_SECTION_NODE: {
            node = factory.createCDATASection(place.getNodeValue());
            break;
        }
        case Node.COMMENT_NODE: {
            node = factory.createComment(place.getNodeValue());
            break;
        }
        case Node.ELEMENT_NODE: {
            Element element = factory.createElement(place.getNodeName());
            node = element;
            NamedNodeMap attrs  = place.getAttributes();
            int attrCount = attrs.getLength();
            for (int i = 0; i < attrCount; i++) {
                Attr attr = (Attr)attrs.item(i);
                String attrName = attr.getNodeName();
                String attrValue = attr.getNodeValue();
                element.setAttribute(attrName, attrValue);
                if (domimpl && !attr.getSpecified()) {
                    ((AttrImpl)element.getAttributeNode(attrName)).setSpecified(false);
                }
            }
            break;
        }
        case Node.ENTITY_REFERENCE_NODE: {
            node = factory.createEntityReference(place.getNodeName());
            break;
        }
        case Node.PROCESSING_INSTRUCTION_NODE: {
            node = factory.createProcessingInstruction(place.getNodeName(),
                    place.getNodeValue());
            break;
        }
        case Node.TEXT_NODE: {
            node = factory.createTextNode(place.getNodeValue());
            break;
        }
        default: {
            throw new IllegalArgumentException("can't copy node type, "+
                    type+" ("+
                    place.getNodeName()+')');
        }
        }
        dest.appendChild(node);

        // iterate over children
        if (place.hasChildNodes()) {
            parent = place;
            place  = place.getFirstChild();
            dest   = node;
        }

        // advance
        else {
            place = place.getNextSibling();
            while (place == null && parent != start) {
                place  = parent.getNextSibling();
                parent = parent.getParentNode();
                dest   = dest.getParentNode();
            }
        }

    }

}
 
Example 18
Source File: DOMUtil.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Copies the source tree into the specified place in a destination
 * tree. The source node and its children are appended as children
 * of the destination node.
 * <p>
 * <em>Note:</em> This is an iterative implementation.
 */
public static void copyInto(Node src, Node dest) throws DOMException {

    // get node factory
    Document factory = dest.getOwnerDocument();
    boolean domimpl = factory instanceof DocumentImpl;

    // placement variables
    Node start  = src;
    Node parent = src;
    Node place  = src;

    // traverse source tree
    while (place != null) {

        // copy this node
        Node node = null;
        int  type = place.getNodeType();
        switch (type) {
        case Node.CDATA_SECTION_NODE: {
            node = factory.createCDATASection(place.getNodeValue());
            break;
        }
        case Node.COMMENT_NODE: {
            node = factory.createComment(place.getNodeValue());
            break;
        }
        case Node.ELEMENT_NODE: {
            Element element = factory.createElement(place.getNodeName());
            node = element;
            NamedNodeMap attrs  = place.getAttributes();
            int attrCount = attrs.getLength();
            for (int i = 0; i < attrCount; i++) {
                Attr attr = (Attr)attrs.item(i);
                String attrName = attr.getNodeName();
                String attrValue = attr.getNodeValue();
                element.setAttribute(attrName, attrValue);
                if (domimpl && !attr.getSpecified()) {
                    ((AttrImpl)element.getAttributeNode(attrName)).setSpecified(false);
                }
            }
            break;
        }
        case Node.ENTITY_REFERENCE_NODE: {
            node = factory.createEntityReference(place.getNodeName());
            break;
        }
        case Node.PROCESSING_INSTRUCTION_NODE: {
            node = factory.createProcessingInstruction(place.getNodeName(),
                    place.getNodeValue());
            break;
        }
        case Node.TEXT_NODE: {
            node = factory.createTextNode(place.getNodeValue());
            break;
        }
        default: {
            throw new IllegalArgumentException("can't copy node type, "+
                    type+" ("+
                    place.getNodeName()+')');
        }
        }
        dest.appendChild(node);

        // iterate over children
        if (place.hasChildNodes()) {
            parent = place;
            place  = place.getFirstChild();
            dest   = node;
        }

        // advance
        else {
            place = place.getNextSibling();
            while (place == null && parent != start) {
                place  = parent.getNextSibling();
                parent = parent.getParentNode();
                dest   = dest.getParentNode();
            }
        }

    }

}
 
Example 19
Source File: SdkRepoSource.java    From javaide with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Helper method used by {@link #findAlternateToolsXml(InputStream)} to duplicate a node
 * and attach it to the given root in the new document.
 */
private Element duplicateNode(Element newRootNode, Element oldNode,
        String namespaceUri, String prefix) {
    // The implementation here is more or less equivalent to
    //
    //    newRoot.appendChild(newDoc.importNode(oldNode, deep=true))
    //
    // except we can't just use importNode() since we need to deal with the fact
    // that the old document is not namespace-aware yet the new one is.

    Document newDoc = newRootNode.getOwnerDocument();
    Element newNode = null;

    String nodeName = oldNode.getNodeName();
    int pos = nodeName.indexOf(':');
    if (pos > 0 && pos < nodeName.length() - 1) {
        nodeName = nodeName.substring(pos + 1);
        newNode = newDoc.createElementNS(namespaceUri, nodeName);
        newNode.setPrefix(prefix);
    } else {
        newNode = newDoc.createElement(nodeName);
    }

    newRootNode.appendChild(newNode);

    // Merge in all the attributes
    NamedNodeMap attrs = oldNode.getAttributes();
    for (int i = 0; i < attrs.getLength(); i++) {
        Attr attr = (Attr) attrs.item(i);
        Attr newAttr = null;

        String attrName = attr.getNodeName();
        pos = attrName.indexOf(':');
        if (pos > 0 && pos < attrName.length() - 1) {
            attrName = attrName.substring(pos + 1);
            newAttr = newDoc.createAttributeNS(namespaceUri, attrName);
            newAttr.setPrefix(prefix);
        } else {
            newAttr = newDoc.createAttribute(attrName);
        }

        newAttr.setNodeValue(attr.getNodeValue());

        if (pos > 0) {
            newNode.getAttributes().setNamedItemNS(newAttr);
        } else {
            newNode.getAttributes().setNamedItem(newAttr);
        }
    }

    // Merge all child elements and texts
    for (Node child = oldNode.getFirstChild(); child != null; child = child.getNextSibling()) {
        if (child.getNodeType() == Node.ELEMENT_NODE) {
            duplicateNode(newNode, (Element) child, namespaceUri, prefix);

        } else if (child.getNodeType() == Node.TEXT_NODE) {
            Text newText = newDoc.createTextNode(child.getNodeValue());
            newNode.appendChild(newText);
        }
    }

    return newNode;
}
 
Example 20
Source File: DOMUtil.java    From Bytecoder with Apache License 2.0 4 votes vote down vote up
/**
 * Copies the source tree into the specified place in a destination
 * tree. The source node and its children are appended as children
 * of the destination node.
 * <p>
 * <em>Note:</em> This is an iterative implementation.
 */
public static void copyInto(Node src, Node dest) throws DOMException {

    // get node factory
    Document factory = dest.getOwnerDocument();
    boolean domimpl = factory instanceof DocumentImpl;

    // placement variables
    Node start  = src;
    Node parent = src;
    Node place  = src;

    // traverse source tree
    while (place != null) {

        // copy this node
        Node node = null;
        int  type = place.getNodeType();
        switch (type) {
        case Node.CDATA_SECTION_NODE: {
            node = factory.createCDATASection(place.getNodeValue());
            break;
        }
        case Node.COMMENT_NODE: {
            node = factory.createComment(place.getNodeValue());
            break;
        }
        case Node.ELEMENT_NODE: {
            Element element = factory.createElement(place.getNodeName());
            node = element;
            NamedNodeMap attrs  = place.getAttributes();
            int attrCount = attrs.getLength();
            for (int i = 0; i < attrCount; i++) {
                Attr attr = (Attr)attrs.item(i);
                String attrName = attr.getNodeName();
                String attrValue = attr.getNodeValue();
                element.setAttribute(attrName, attrValue);
                if (domimpl && !attr.getSpecified()) {
                    ((AttrImpl)element.getAttributeNode(attrName)).setSpecified(false);
                }
            }
            break;
        }
        case Node.ENTITY_REFERENCE_NODE: {
            node = factory.createEntityReference(place.getNodeName());
            break;
        }
        case Node.PROCESSING_INSTRUCTION_NODE: {
            node = factory.createProcessingInstruction(place.getNodeName(),
                    place.getNodeValue());
            break;
        }
        case Node.TEXT_NODE: {
            node = factory.createTextNode(place.getNodeValue());
            break;
        }
        default: {
            throw new IllegalArgumentException("can't copy node type, "+
                    type+" ("+
                    place.getNodeName()+')');
        }
        }
        dest.appendChild(node);

        // iterate over children
        if (place.hasChildNodes()) {
            parent = place;
            place  = place.getFirstChild();
            dest   = node;
        }

        // advance
        else {
            place = place.getNextSibling();
            while (place == null && parent != start) {
                place  = parent.getNextSibling();
                parent = parent.getParentNode();
                dest   = dest.getParentNode();
            }
        }

    }

}