Example usage for org.w3c.dom Element setAttribute

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

Introduction

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

Prototype

public void setAttribute(String name, String value) throws DOMException;

Source Link

Document

Adds a new attribute.

Usage

From source file:de.fhg.iais.asc.xslt.binaries.DownloadAndScale.java

private static void copyAttributes(Node source, Element target, Iterable<String> attributeNames) {
    final NamedNodeMap sourceAttributes = source.getAttributes();

    if (sourceAttributes != null) {
        for (String attrName : attributeNames) {
            final Node inputAttr = sourceAttributes.getNamedItem(attrName);

            if (inputAttr != null) {
                target.setAttribute(attrName, inputAttr.getNodeValue());
            }/*from w  w  w  .  j  a v a 2s  .c om*/
        }
    }
}

From source file:net.sourceforge.eclipsetrader.charts.ChartsPlugin.java

public static void saveDefaultChart(Chart chart) {
    Log logger = LogFactory.getLog(ChartsPlugin.class);
    SimpleDateFormat dateTimeFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); //$NON-NLS-1$

    try {// w ww  .  j a  v  a 2 s. c  om
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document document = builder.getDOMImplementation().createDocument(null, "chart", null); //$NON-NLS-1$

        Element root = document.getDocumentElement();

        Element node = document.createElement("title"); //$NON-NLS-1$
        node.appendChild(document.createTextNode(chart.getTitle()));
        root.appendChild(node);
        node = document.createElement("compression"); //$NON-NLS-1$
        node.appendChild(document.createTextNode(String.valueOf(chart.getCompression())));
        root.appendChild(node);
        node = document.createElement("period"); //$NON-NLS-1$
        node.appendChild(document.createTextNode(String.valueOf(chart.getPeriod())));
        root.appendChild(node);
        node = document.createElement("autoScale"); //$NON-NLS-1$
        node.appendChild(document.createTextNode(String.valueOf(chart.isAutoScale())));
        root.appendChild(node);
        if (chart.getBeginDate() != null) {
            node = document.createElement("begin"); //$NON-NLS-1$
            node.appendChild(document.createTextNode(dateTimeFormat.format(chart.getBeginDate())));
            root.appendChild(node);
        }
        if (chart.getEndDate() != null) {
            node = document.createElement("end"); //$NON-NLS-1$
            node.appendChild(document.createTextNode(dateTimeFormat.format(chart.getEndDate())));
            root.appendChild(node);
        }
        for (int r = 0; r < chart.getRows().size(); r++) {
            ChartRow row = (ChartRow) chart.getRows().get(r);
            row.setId(new Integer(r));

            Element rowNode = document.createElement("row"); //$NON-NLS-1$
            root.appendChild(rowNode);

            for (int t = 0; t < row.getTabs().size(); t++) {
                ChartTab tab = (ChartTab) row.getTabs().get(t);
                tab.setId(new Integer(t));

                Element tabNode = document.createElement("tab"); //$NON-NLS-1$
                tabNode.setAttribute("label", tab.getLabel()); //$NON-NLS-1$
                rowNode.appendChild(tabNode);

                for (int i = 0; i < tab.getIndicators().size(); i++) {
                    ChartIndicator indicator = (ChartIndicator) tab.getIndicators().get(i);
                    indicator.setId(new Integer(i));

                    Element indicatorNode = document.createElement("indicator"); //$NON-NLS-1$
                    indicatorNode.setAttribute("pluginId", indicator.getPluginId()); //$NON-NLS-1$
                    tabNode.appendChild(indicatorNode);

                    for (Iterator iter = indicator.getParameters().keySet().iterator(); iter.hasNext();) {
                        String key = (String) iter.next();

                        node = document.createElement("param"); //$NON-NLS-1$
                        node.setAttribute("key", key); //$NON-NLS-1$
                        node.setAttribute("value", (String) indicator.getParameters().get(key)); //$NON-NLS-1$
                        indicatorNode.appendChild(node);
                    }
                }

                for (int i = 0; i < tab.getObjects().size(); i++) {
                    ChartObject object = (ChartObject) tab.getObjects().get(i);
                    object.setId(new Integer(i));

                    Element indicatorNode = document.createElement("object"); //$NON-NLS-1$
                    indicatorNode.setAttribute("pluginId", object.getPluginId()); //$NON-NLS-1$
                    tabNode.appendChild(indicatorNode);

                    for (Iterator iter = object.getParameters().keySet().iterator(); iter.hasNext();) {
                        String key = (String) iter.next();

                        node = document.createElement("param"); //$NON-NLS-1$
                        node.setAttribute("key", key); //$NON-NLS-1$
                        node.setAttribute("value", (String) object.getParameters().get(key)); //$NON-NLS-1$
                        indicatorNode.appendChild(node);
                    }
                }
            }
        }

        TransformerFactory factory = TransformerFactory.newInstance();
        try {
            factory.setAttribute("indent-number", new Integer(4)); //$NON-NLS-1$
        } catch (Exception e) {
        }
        Transformer transformer = factory.newTransformer();
        transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
        transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1"); //$NON-NLS-1$
        transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
        transformer.setOutputProperty("{http\u003a//xml.apache.org/xslt}indent-amount", "4"); //$NON-NLS-1$ //$NON-NLS-2$
        DOMSource source = new DOMSource(document);

        File file = ChartsPlugin.getDefault().getStateLocation().append("defaultChart.xml").toFile(); //$NON-NLS-1$

        BufferedWriter out = new BufferedWriter(new FileWriter(file));
        StreamResult result = new StreamResult(out);
        transformer.transform(source, result);
        out.flush();
        out.close();

    } catch (Exception e) {
        logger.error(e.toString(), e);
    }
}

From source file:Main.java

/**
 * 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./*from ww w . j  a  v  a2  s.com*/
 * <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 + " (" + node.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();
            }
        }

    }

}

From source file:de.akra.idocit.wsdl.services.DocumentationGenerator.java

/**
 * Wraps the addressees with their individual documentation into a docpart
 * {@link Element}, sets the attributes of the {@link Element} and returns it.
 * //w w  w  . j  a  v  a2s. co m
 * @param documentation
 *            {@link Documentation} whose addressees should be generated to Elements.
 * @return The generated docpart {@link Element}, null if <code>domDocument</code> is
 *         not initialized.
 */
private static Element generateDocpartElement(Documentation documentation) {
    Element docpart = null;
    // Without DOM Document you can not create new elements. It should be
    // initialized in generateDocElement().
    if (domDocument != null) {
        docpart = domDocument.createElement(DocumentationParser.DOCPART_TAG_NAME);

        // set attributes
        if (documentation.getThematicRole() != null) {
            docpart.setAttribute(THEMATIC_ROLE_ATTRIBUTE_NAME, documentation.getThematicRole().getName());
        }

        // set error documentation flag
        if (documentation.getThematicRole() != null) {
            docpart.setAttribute(ERROR_DOCUMENTATION_ATTRIBUTE_NAME,
                    String.valueOf(documentation.isErrorCase()));
        }

        if (documentation.getSignatureElementIdentifier() != null) {
            docpart.setAttribute(SIGNATURE_ELEMENT_ATTRIBUTE_NAME,
                    documentation.getSignatureElementIdentifier());
        }

        // insert addressee elements
        Map<Addressee, String> addresseeDocs = documentation.getDocumentation();
        List<Addressee> addresseeSequence = documentation.getAddresseeSequence();
        for (Addressee addressee : addresseeSequence) {
            Element addrElem = domDocument.createElement(ADDRESSEE_ELEMENT_NAME);
            addrElem.setAttribute(ADDRESSEE_GROUP_ATTRIBUTE_NAME, addressee.getName());

            addTextAsNodes(addrElem, addresseeDocs.get(addressee));
            docpart.appendChild(addrElem);
        }
    } else {
        logger.log(Level.SEVERE, "domDocument is no initialized.");
    }
    return docpart;
}

From source file:Main.java

/**
 * Convenience method to copy the contents of the old {@link Node} into the
 * new one./*from  w w  w . j a v a2s .c o  m*/
 * 
 * @param newDoc
 * @param newNode
 * @param oldParent
 */
public static void copyContents(Document newDoc, Node newNode, Node oldNode) {
    // FIXME we should be able to achieve this with much less code (e.g.
    // the code commented out) but for some reason there are
    // incompatibility issues being spat out by the tests.
    //      final NodeList childNodes = oldNode.getChildNodes();
    //        for (int i = 0; i < childNodes.getLength(); i++) {
    //           final Node child = newDoc.importNode(childNodes.item(i), true);
    //           newNode.appendChild(child);
    //        }

    final NodeList childs = oldNode.getChildNodes();

    for (int i = 0; i < childs.getLength(); i++) {
        final Node child = childs.item(i);
        Element newElem = null;
        switch (child.getNodeType()) {
        case Node.ELEMENT_NODE:
            //Get all the attributes of an element in a map
            final NamedNodeMap attrs = child.getAttributes();

            // Process each attribute
            newElem = newDoc.createElement(child.getNodeName());
            for (int j = 0; j < attrs.getLength(); j++) {
                final Attr attr = (Attr) attrs.item(j);
                // add attribute name and value to the new element
                newElem.setAttribute(attr.getNodeName(), attr.getNodeValue());
            }
            newNode.appendChild(newElem);
            break;

        case Node.TEXT_NODE:
            newNode.appendChild(newDoc.createTextNode(getString(child)));
        }
        copyContents(newDoc, newElem, child);
    }
}

From source file:com.ibm.soatf.component.soap.builder.XmlUtils.java

public static InputStream fixSchemaFile(File schemaFile) throws XmlException, IOException {
    XmlObject xmlObject = XmlObject.Factory.parse(schemaFile);
    XmlObject[] booleanTypes = xmlObject.selectPath(
            "$this//*[local-name()=\"restriction\" and contains(@base,'xsd:boolean') and *[local-name()=\"pattern\"]]");
    for (XmlObject boolType : booleanTypes) {
        Node node = boolType.getDomNode();
        short nodeType = node.getNodeType();
        if (nodeType == Node.ELEMENT_NODE) {
            Element e = (Element) node;
            e.setAttribute("base", "xsd:int");
        }/*from w  w w  .j a  va2  s  .  c  o m*/
    }
    return xmlObject.newInputStream();
}

From source file:de.betterform.xml.xforms.ui.state.UIElementStateUtil.java

/**
 * Creates or updates the specified state attribute. If the value is
 * <code>null</code>, the attribute will be removed.
 *
 * @param element the element.//from  w  w w  .  j  a va  2s. c  om
 * @param name    the attribute name.
 * @param value   the attribute value.
 */
public static void setStateAttribute(Element element, String name, String value) {
    if (value != null) {
        element.setAttribute(name, value);
    } else {
        element.removeAttribute(name);
    }
}

From source file:com.ibm.soatf.component.soap.builder.XmlUtils.java

public static String setTextToElementAttribute(String xmlText, String xPath, String attrName,
        String attrValue) {//  www  . j  a va  2  s .c  o m
    if (xmlText == null || xPath == null || attrName == null) {
        return xmlText;
    }
    try {
        XmlObject xmlObject = XmlObject.Factory.parse(xmlText);

        /*String namespaces = declareXPathNamespaces(xmlObject);
        if (namespaces != null && namespaces.trim().length() > 0)
        xPath = namespaces + xPath;*/

        XmlObject[] path = xmlObject.selectPath(xPath);
        if (path == null || path.length != 1 || path[0].getDomNode() == null) {
            return xmlText;
        }
        Node node = path[0].getDomNode();
        short nodeType = node.getNodeType();
        if (nodeType == Node.ELEMENT_NODE) {
            Element e = (Element) node;
            e.setAttribute(attrName, attrValue);
        }
        return xmlObject.toString();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return xmlText;
}

From source file:it.intecs.pisa.toolbox.util.URLReader.java

public static void getContent(String url, Document urlTree, Element fatherNode) throws Exception {
    Element directoryNode = urlTree.createElement("directory");
    directoryNode.setAttribute("name", url);
    fatherNode.appendChild(directoryNode);
    try {/*from   ww  w .jav a  2 s.c  o m*/
        String[] filesToDw = URLReader.getFileToDW("/" + SCHEMA + url);
        int index = 0;
        while (index < filesToDw.length) {
            Element fileNode = urlTree.createElement("file");
            fileNode.setAttribute("name", filesToDw[index]);
            directoryNode.appendChild(fileNode);
            index++;
        }

        String[] directoryToDw = URLReader.getDirectoryToDW("/" + SCHEMA + url);
        index = 0;
        while (index < directoryToDw.length) {
            getContent(directoryToDw[index], urlTree, directoryNode);
            index++;
        }
    } catch (Exception e) {
        e.printStackTrace(System.out);
    }
}

From source file:com.osafe.services.SiteMapServices.java

private static void createFriendlyMapNode(String URL, ProductContentWrapper productContentWrapper,
        CategoryContentWrapper categoryContentWrapper, CategoryContentWrapper parentCategoryContentWrapper,
        String featureDescription, String contentSeoFriendlyName) {

    StringBuilder urlBuilder = new StringBuilder();
    String productName = null;/*from   w w w.j ava  2 s.com*/
    String parentCategoryName = null;
    String categoryName = null;
    String friendlyKey = null;
    String friendlyValue = null;
    StringBuilder friendlyKeyValue = new StringBuilder();

    try {
        List<String> pathElements = StringUtil.split(URL, "/");
        String sUrlTarget = pathElements.get(pathElements.size() - 1);

        friendlyKey = StringUtil.replaceString(sUrlTarget, "&", "~");
        friendlyKey = StringUtil.replaceString(friendlyKey, "=", "^^");

        if (productContentWrapper != null) {
            productName = productContentWrapper.get("PRODUCT_NAME").toString();
        }

        if (parentCategoryContentWrapper != null) {
            parentCategoryName = parentCategoryContentWrapper.get("CATEGORY_NAME").toString();
        }

        if (categoryContentWrapper != null) {
            categoryName = categoryContentWrapper.get("CATEGORY_NAME").toString();
        }

        if (UtilValidate.isNotEmpty(parentCategoryName)) {
            friendlyKeyValue.append(parentCategoryName + "/");
        }

        if (UtilValidate.isNotEmpty(categoryName)) {
            friendlyKeyValue.append(categoryName);
        }

        if (UtilValidate.isNotEmpty(productName)) {
            if (UtilValidate.isNotEmpty(featureDescription)) {
                productName = productName + " " + featureDescription;
            }
            friendlyKeyValue.append("/" + productName);
        }
        if (UtilValidate.isNotEmpty(contentSeoFriendlyName)) {
            friendlyKeyValue.append(contentSeoFriendlyName);
        }
        friendlyValue = friendlyKeyValue.toString();
        friendlyValue = StringUtil.replaceString(friendlyValue, "&apos;", "");
        friendlyValue = StringUtil.replaceString(friendlyValue, "'", "");
        friendlyValue = StringUtil.replaceString(friendlyValue, "&quot;", "");
        friendlyValue = StringUtil.replaceString(friendlyValue, "\"", "");
        friendlyValue = StringUtil.replaceString(friendlyValue, "&amp;", "And");
        friendlyValue = StringUtil.replaceString(friendlyValue, "&", "And");
        friendlyValue = StringUtil.replaceString(friendlyValue, ",", "");
        //Do not replace '-' if this was a static page friendly name (contentAttribute type=SEO_FRIENDLY_URL) 
        if (UtilValidate.isEmpty(contentSeoFriendlyName)) {
            friendlyValue = StringUtil.replaceString(friendlyValue, "-", "");
        }
        friendlyValue = StringUtil.replaceString(friendlyValue, ".", "");
        friendlyValue = StringUtil.replaceString(friendlyValue, " ", "-");

        Element newElement = document.createElement("property");
        newElement.setAttribute("key", friendlyKey);
        Element newChildElement = document.createElement("value");
        newChildElement.setAttribute("xml:lang", "en");
        newChildElement.appendChild(document.createTextNode(friendlyValue.toLowerCase()));
        newElement.appendChild(newChildElement);
        rootElement.appendChild(newElement);

    } catch (Exception e) {
        Debug.logError(e, module);

    }
}