Example usage for org.w3c.dom Element setAttributeNode

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

Introduction

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

Prototype

public Attr setAttributeNode(Attr newAttr) throws DOMException;

Source Link

Document

Adds a new attribute node.

Usage

From source file:Main.java

/**
 * recursively transform the prefix and the namespace of a node where getNamespaceURI is NULL
 * @param node the node to transform/*from w  w  w.  j  av  a2 s. c  o  m*/
 * @param prefix the new prefix
 * @param namespaceuri the new namespace uri
 * @return the new node with NS and prefix changed
 */
static public Node setPrefixNamespace(Node node, String prefix, String namespaceuri) {
    Node dest = null;
    if (node.getNodeType() == Node.ELEMENT_NODE) {
        Element e = (Element) node;
        if (e.getNamespaceURI() == null) {

            Element e2 = node.getOwnerDocument().createElementNS(namespaceuri,
                    (prefix != null ? prefix + ':' + e.getLocalName() : e.getLocalName()));
            NamedNodeMap nodes = e.getAttributes();
            for (int i = 0; i < nodes.getLength(); ++i) {
                Attr att = (Attr) (node.getOwnerDocument().importNode(nodes.item(i), true));
                e2.setAttributeNode(att);
            }
            dest = e2;
        } else {
            dest = node.getOwnerDocument().importNode(node, false);
        }
    } else {
        dest = node.getOwnerDocument().importNode(node, false);
    }

    for (Node c = node.getFirstChild(); c != null; c = c.getNextSibling()) {
        dest.appendChild(setPrefixNamespace(c, prefix, namespaceuri));
    }
    return dest;
}

From source file:Main.java

/**
 * Clone given Node into target Document. If targe is null, same Document will be used.
 * If deep is specified, all children below will also be cloned.
 *//*  w  ww .  java  2  s  .  c  om*/
public final static Node cloneNode(Node node, Document target, boolean deep) throws DOMException {
    if ((target == null) || (node.getOwnerDocument() == target)) {
        // same Document
        return node.cloneNode(deep);
    } else {
        //DOM level 2 provides this in Document, so once xalan switches to that,
        //we can take out all the below and just call target.importNode(node, deep);
        //For now, we implement based on the javadocs for importNode
        Node newNode;
        int nodeType = node.getNodeType();

        switch (nodeType) {
        case Node.ATTRIBUTE_NODE:
            newNode = target.createAttribute(node.getNodeName());

            break;

        case Node.DOCUMENT_FRAGMENT_NODE:
            newNode = target.createDocumentFragment();

            break;

        case Node.ELEMENT_NODE:

            Element newElement = target.createElement(node.getNodeName());
            NamedNodeMap nodeAttr = node.getAttributes();

            if (nodeAttr != null) {
                for (int i = 0; i < nodeAttr.getLength(); i++) {
                    Attr attr = (Attr) nodeAttr.item(i);

                    if (attr.getSpecified()) {
                        Attr newAttr = (Attr) cloneNode(attr, target, true);
                        newElement.setAttributeNode(newAttr);
                    }
                }
            }

            newNode = newElement;

            break;

        case Node.ENTITY_REFERENCE_NODE:
            newNode = target.createEntityReference(node.getNodeName());

            break;

        case Node.PROCESSING_INSTRUCTION_NODE:
            newNode = target.createProcessingInstruction(node.getNodeName(), node.getNodeValue());

            break;

        case Node.TEXT_NODE:
            newNode = target.createTextNode(node.getNodeValue());

            break;

        case Node.CDATA_SECTION_NODE:
            newNode = target.createCDATASection(node.getNodeValue());

            break;

        case Node.COMMENT_NODE:
            newNode = target.createComment(node.getNodeValue());

            break;

        case Node.NOTATION_NODE:
        case Node.ENTITY_NODE:
        case Node.DOCUMENT_TYPE_NODE:
        case Node.DOCUMENT_NODE:
        default:
            throw new IllegalArgumentException("Importing of " + node + " not supported yet");
        }

        if (deep) {
            for (Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) {
                newNode.appendChild(cloneNode(child, target, true));
            }
        }

        return newNode;
    }
}

From source file:Main.java

/**
 * Clone given Node into target Document. If targe is null, same Document will be used.
 * If deep is specified, all children below will also be cloned.
 *//*  w  ww . j  a v  a 2s.  co m*/
public static Node cloneNode(Node node, Document target, boolean deep) throws DOMException {
    if (target == null || node.getOwnerDocument() == target)
        // same Document
        return node.cloneNode(deep);
    else {
        //DOM level 2 provides this in Document, so once xalan switches to that,
        //we can take out all the below and just call target.importNode(node, deep);
        //For now, we implement based on the javadocs for importNode
        Node newNode;
        int nodeType = node.getNodeType();

        switch (nodeType) {
        case Node.ATTRIBUTE_NODE:
            newNode = target.createAttribute(node.getNodeName());

            break;

        case Node.DOCUMENT_FRAGMENT_NODE:
            newNode = target.createDocumentFragment();

            break;

        case Node.ELEMENT_NODE:

            Element newElement = target.createElement(node.getNodeName());
            NamedNodeMap nodeAttr = node.getAttributes();

            if (nodeAttr != null)
                for (int i = 0; i < nodeAttr.getLength(); i++) {
                    Attr attr = (Attr) nodeAttr.item(i);

                    if (attr.getSpecified()) {
                        Attr newAttr = (Attr) cloneNode(attr, target, true);
                        newElement.setAttributeNode(newAttr);
                    }
                }

            newNode = newElement;

            break;

        case Node.ENTITY_REFERENCE_NODE:
            newNode = target.createEntityReference(node.getNodeName());

            break;

        case Node.PROCESSING_INSTRUCTION_NODE:
            newNode = target.createProcessingInstruction(node.getNodeName(), node.getNodeValue());

            break;

        case Node.TEXT_NODE:
            newNode = target.createTextNode(node.getNodeValue());

            break;

        case Node.CDATA_SECTION_NODE:
            newNode = target.createCDATASection(node.getNodeValue());

            break;

        case Node.COMMENT_NODE:
            newNode = target.createComment(node.getNodeValue());

            break;

        case Node.NOTATION_NODE:
        case Node.ENTITY_NODE:
        case Node.DOCUMENT_TYPE_NODE:
        case Node.DOCUMENT_NODE:
        default:
            throw new IllegalArgumentException("Importing of " + node + " not supported yet");
        }

        if (deep)
            for (Node child = node.getFirstChild(); child != null; child = child.getNextSibling())
                newNode.appendChild(cloneNode(child, target, true));

        return newNode;
    }
}

From source file:Main.java

/**
 * Add a CDATA element with attributes./* w w w . j a  v a  2  s  .  c  o  m*/
 * <p/>
 * NOTE: Serializing a XML document via TRAX changes "\r\n" to "\r\r\n" in
 * a CDATA section. Serializing with the Xalan XMLSerializer works fine.
 *
 * @param parent parent node
 * @param name   node name
 * @param data   node data
 * @param attrs  attributes
 */
public static Element addCDATAElement(Node parent, String name, String data, Attr[] attrs) {
    Element element;
    CDATASection cdata;
    if (parent instanceof Document) {
        element = ((Document) parent).createElement(name);
        /*
         * Creates a <code>CDATASection</code> node whose value is the
         * specified.
         */
        cdata = ((Document) parent).createCDATASection(data);
    } else {
        element = parent.getOwnerDocument().createElement(name);
        cdata = parent.getOwnerDocument().createCDATASection(data);
    }

    if (attrs != null && attrs.length > 0) {
        for (Attr attr : attrs) {
            element.setAttributeNode(attr);
        }
    }

    element.appendChild(cdata);
    parent.appendChild(element);
    return element;
}

From source file:Main.java

/**
 * Copies all attributes from one element to another in the official way.
 *//*from w  ww.j ava  2  s  .  com*/
public static void copyAttributes(Element elementFrom, Element elementTo) {
    NamedNodeMap nodeList = elementFrom.getAttributes();
    if (nodeList == null) {
        // No attributes to copy: just return
        return;
    }

    Attr attrFrom = null;
    Attr attrTo = null;

    // Needed as factory to create attrs
    Document documentTo = elementTo.getOwnerDocument();
    int len = nodeList.getLength();

    // Copy each attr by making/setting a new one and
    // adding to the target element.
    for (int i = 0; i < len; i++) {
        attrFrom = (Attr) nodeList.item(i);

        // Create an set value
        attrTo = documentTo.createAttribute(attrFrom.getName());
        attrTo.setValue(attrFrom.getValue());

        // Set in target element
        elementTo.setAttributeNode(attrTo);
    }
}

From source file:BuildXml.java

public Node createContactNode(Document document) {

    // create FirstName and LastName elements
    Element firstName = document.createElement("FirstName");
    Element lastName = document.createElement("LastName");

    firstName.appendChild(document.createTextNode("First Name"));
    lastName.appendChild(document.createTextNode("Last Name"));

    // create contact element
    Element contact = document.createElement("contact");

    // create attribute
    Attr genderAttribute = document.createAttribute("gender");
    genderAttribute.setValue("F");

    // append attribute to contact element
    contact.setAttributeNode(genderAttribute);
    contact.appendChild(firstName);/*from  ww w. j  a v a2s .c  o m*/
    contact.appendChild(lastName);

    return contact;
}

From source file:com.dinochiesa.edgecallouts.EditXmlNode.java

private void insertBefore(NodeList nodes, Node newNode, short newNodeType) {
    Node currentNode = nodes.item(0);
    switch (newNodeType) {
    case Node.ATTRIBUTE_NODE:
        Element parent = ((Attr) currentNode).getOwnerElement();
        parent.setAttributeNode((Attr) newNode);
        break;//  w w  w  . j a v a2 s .  c  o  m
    case Node.ELEMENT_NODE:
        currentNode.getParentNode().insertBefore(newNode, currentNode);
        break;
    case Node.TEXT_NODE:
        String v = currentNode.getNodeValue();
        currentNode.setNodeValue(newNode.getNodeValue() + v);
        break;
    }
}

From source file:com.dinochiesa.edgecallouts.EditXmlNode.java

private void append(NodeList nodes, Node newNode, short newNodeType) {
    Node currentNode = nodes.item(0);
    switch (newNodeType) {
    case Node.ATTRIBUTE_NODE:
        Element parent = ((Attr) currentNode).getOwnerElement();
        parent.setAttributeNode((Attr) newNode);
        break;/*from  ww w.  j  av a 2 s .c  o  m*/
    case Node.ELEMENT_NODE:
        currentNode.appendChild(newNode);
        break;
    case Node.TEXT_NODE:
        if (currentNode.getNodeType() != Node.TEXT_NODE) {
            throw new IllegalStateException("wrong source node type.");
        }
        String v = currentNode.getNodeValue();
        currentNode.setNodeValue(v + newNode.getNodeValue());
        break;
    }
}

From source file:gov.medicaid.services.impl.FileNetServiceBean.java

/**
 * Creates the XML./*from ww  w .j  ava 2s  . c  o  m*/
 * 
 * @param outFile
 *            the output file handler
 * @param attributes
 *            the content
 * @throws PortalServiceException
 *             if any error occurs
 */
private void createXML(File outFile, Map<String, String> attributes) throws PortalServiceException {
    try {
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        // root elements
        Document doc = docBuilder.newDocument();
        Element rootElement = doc.createElement("Document");
        doc.appendChild(rootElement);
        for (String key : attributes.keySet()) {
            Element indexVal = doc.createElement("Indexvalue");
            Attr attr = doc.createAttribute("name");
            attr.setValue(key);
            indexVal.setAttributeNode(attr);
            if (attributes.get(key) != null) {
                indexVal.appendChild(doc.createTextNode(attributes.get(key)));
            }
            rootElement.appendChild(indexVal);
        }
        // write the content into xml file
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(outFile);

        transformer.transform(source, result);

    } catch (ParserConfigurationException e) {
        throw new PortalServiceException("Failed to create FileNet xml", e);
    } catch (TransformerException e) {
        throw new PortalServiceException("Failed to create FileNet xml", e);
    }

}

From source file:de.uzk.hki.da.metadata.MetadataStructure.java

private void addXmlNsToEDM(Document edmDoc, Element rootElement) {
    Attr xmlns_dc = edmDoc.createAttribute("xmlns:dc");
    xmlns_dc.setValue(C.DC_NS.getURI());
    rootElement.setAttributeNode(xmlns_dc);

    Attr xmlns_edm = edmDoc.createAttribute("xmlns:edm");
    xmlns_edm.setValue(C.EDM_NS.getURI());
    rootElement.setAttributeNode(xmlns_edm);

    Attr xmlns_dcterms = edmDoc.createAttribute("xmlns:dcterms");
    xmlns_dcterms.setValue(C.DCTERMS_NS.getURI());
    rootElement.setAttributeNode(xmlns_dcterms);

    Attr xmlns_rdf = edmDoc.createAttribute("xmlns:rdf");
    xmlns_rdf.setValue(C.RDF_NS.getURI());
    rootElement.setAttributeNode(xmlns_rdf);

    Attr xmlns_ore = edmDoc.createAttribute("xmlns:ore");
    xmlns_ore.setValue(C.ORE_NS.getURI());
    rootElement.setAttributeNode(xmlns_ore);
}