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:Main.java

/**
 * Qualification of every element in a DOM document. Previous namespaces are
 * ignored.//from  ww w.  j a v a  2 s .  c  o  m
 * 
 * @param document
 *            The document to modify.
 * @param namespaces
 *            A map of prefix/URL where prefix are expected to match the
 *            local name of the elements they qualify (if an element has no
 *            corresponding prefix, it uses the namespace of its parent).
 */
public static void autoQualify(Document document, Map<String, String> namespaces) {
    Element root = document.getDocumentElement();
    for (Map.Entry<String, String> entry : namespaces.entrySet()) {
        String prefix = entry.getKey();
        String url = entry.getValue();
        StringBuilder attributName = new StringBuilder("xmlns");
        if (prefix != null) {
            attributName.append(':').append(prefix);
        }
        root.setAttribute(attributName.toString(), url);
    }
    autoQualify(document, root, namespaces, null);
}

From source file:Main.java

/**
 * Adds a new {@link Element} with multiple attributes to the given parent
 * {@link Element}. The attribute data should be passed in via a {@link Map},
 * with each entry containing an attribute name as key and attribute value as the value.
 * /*  w w  w  .  j  ava2 s.  co m*/
 * @param doc
 * @param parent
 * @param name
 * @param attributeData
 * @return
 */
public static Element addElement(Document doc, Node parent, String name, Map<String, String> attributeData) {
    if (doc == null) {
        doc = parent.getOwnerDocument();
    }
    final Element elem = addElement(doc, parent, name);
    if (null != attributeData && !attributeData.isEmpty()) {
        Iterator<Map.Entry<String, String>> iter = attributeData.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry<String, String> entry = iter.next();
            elem.setAttribute(entry.getKey(), entry.getValue());
        }
    }
    return elem;
}

From source file:sep.gaia.resources.poi.POILoaderWorker.java

/**
 * Returns an element to limit a query to a specific geographical area.
 * @param doc The document to create the element in.
 * @param bbox The boundaries of the queries area.
 * @return The bounding-box-element ready to be added to a query.
 *//*  w w w  .j av a2  s . c om*/
private static Element createBBoxElement(Document doc, FloatBoundingBox bbox) {
    // The Overpass-API does use sides instead of corners, so convert them:
    float east = bbox.getUpperRight().getY();
    float west = bbox.getLowerRight().getY();
    float north = bbox.getUpperLeft().getX();
    float south = bbox.getLowerRight().getX();

    // Create the element and add the attributes describing the sides of the bbox:
    Element element = doc.createElement("bbox-query");
    element.setAttribute("e", Float.toString(Math.max(east, west)));
    element.setAttribute("w", Float.toString(Math.min(east, west)));
    element.setAttribute("n", Float.toString(Math.max(north, south)));
    element.setAttribute("s", Float.toString(Math.min(north, south)));
    return element;
}

From source file:com.wavemaker.tools.pws.install.PwsInstall.java

public static Document insertImport(Document doc, String resource) {
    List<Node> targetList = new ArrayList<Node>();

    // First, delete old lines if any.

    NodeList list = doc.getElementsByTagName("import");
    Node node = null;/*from  w  ww  . ja va  2s.  c o  m*/
    for (int i = 0; i < list.getLength(); i++) {
        node = list.item(i);
        NamedNodeMap attributes = node.getAttributes();
        for (int j = 0; j < attributes.getLength(); j++) {
            Node attr = attributes.item(j);
            if (attr.getNodeName().equals("resource") && attr.getNodeValue().equals(resource)) {
                targetList.add(node);
                break;
            }
        }
    }

    NodeList beans_list = doc.getElementsByTagName("beans");
    Node beans_node = beans_list.item(0);

    if (targetList.size() > 0) {
        for (Node target : targetList) {
            beans_node.removeChild(target);
        }
    }

    // Now, add the new line

    NodeList list1 = beans_node.getChildNodes();
    Node bean_node = null;
    for (int i = 0; i < list1.getLength(); i++) {
        Node node1 = list1.item(i);
        if (node1.getNodeName().equals("bean")) {
            bean_node = node1;
            break;
        }
    }

    Element elem = doc.createElement("import");
    elem.setAttribute("resource", resource);

    try {
        if (bean_node != null) {
            beans_node.insertBefore(elem, bean_node);
        } else {
            beans_node.appendChild(elem);
        }
    } catch (DOMException ex) {
        ex.printStackTrace();
    }

    return doc;
}

From source file:es.gob.afirma.signers.ooxml.be.fedict.eid.applet.service.signer.ooxml.AbstractOOXMLSignatureService.java

private static void addOriginSigsRels(final String signatureZipEntryName, final ZipOutputStream zipOutputStream)
        throws ParserConfigurationException, IOException, TransformerException {
    final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);

    final Document originSignRelsDocument = documentBuilderFactory.newDocumentBuilder().newDocument();

    final Element relationshipsElement = originSignRelsDocument.createElementNS(RELATIONSHIPS_SCHEMA,
            "Relationships"); //$NON-NLS-1$
    relationshipsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", RELATIONSHIPS_SCHEMA); //$NON-NLS-1$
    originSignRelsDocument.appendChild(relationshipsElement);

    final Element relationshipElement = originSignRelsDocument.createElementNS(RELATIONSHIPS_SCHEMA,
            "Relationship"); //$NON-NLS-1$
    final String relationshipId = "rel-" + UUID.randomUUID().toString(); //$NON-NLS-1$
    relationshipElement.setAttribute("Id", relationshipId); //$NON-NLS-1$
    relationshipElement.setAttribute("Type", //$NON-NLS-1$
            "http://schemas.openxmlformats.org/package/2006/relationships/digital-signature/signature"); //$NON-NLS-1$

    relationshipElement.setAttribute("Target", FilenameUtils.getName(signatureZipEntryName)); //$NON-NLS-1$
    relationshipsElement.appendChild(relationshipElement);

    zipOutputStream.putNextEntry(new ZipEntry("_xmlsignatures/_rels/origin.sigs.rels")); //$NON-NLS-1$
    writeDocumentNoClosing(originSignRelsDocument, zipOutputStream, false);
}

From source file:jp.co.opentone.bsol.framework.core.generator.excel.strategy.XmlWorkbookGeneratorStrategy.java

/**
 * ???.//from w  ww .  j  ava  2s . c  o m
 * @param e ?
 * @param name ??
 * @param value 
 */
private static void setAttribute(Element e, String name, Object value) {
    e.setAttribute(name, String.valueOf(value));
}

From source file:com.google.visualization.datasource.render.HtmlRenderer.java

/**
 * Generates an HTML string representation of a data table.
 * /*ww  w.java 2  s. c  om*/
 * @param dataTable The data table to render.
 * @param locale The locale. If null, uses the default from
 *     {@code LocaleUtil#getDefaultLocale}.
 *
 * @return The char sequence with the html string.
 */
public static CharSequence renderDataTable(DataTable dataTable, ULocale locale) {
    // Create an xml document with head and an empty body.
    Document document = createDocument();
    Element bodyElement = appendHeadAndBody(document);

    // Populate the xml document.
    Element tableElement = document.createElement("table");
    bodyElement.appendChild(tableElement);
    tableElement.setAttribute("border", "1");
    tableElement.setAttribute("cellpadding", "2");
    tableElement.setAttribute("cellspacing", "0");

    // Labels tr element.
    List<ColumnDescription> columnDescriptions = dataTable.getColumnDescriptions();
    Element trElement = document.createElement("tr");
    trElement.setAttribute("style", "font-weight: bold; background-color: #aaa;");
    for (ColumnDescription columnDescription : columnDescriptions) {
        Element tdElement = document.createElement("td");
        tdElement.setTextContent(columnDescription.getLabel());
        trElement.appendChild(tdElement);
    }
    tableElement.appendChild(trElement);

    Map<ValueType, ValueFormatter> formatters = ValueFormatter.createDefaultFormatters(locale);
    // Table tr elements.
    int rowCount = 0;
    for (TableRow row : dataTable.getRows()) {
        rowCount++;
        trElement = document.createElement("tr");
        String backgroundColor = (rowCount % 2 != 0) ? "#f0f0f0" : "#ffffff";
        trElement.setAttribute("style", "background-color: " + backgroundColor);

        List<TableCell> cells = row.getCells();
        for (int c = 0; c < cells.size(); c++) {
            ValueType valueType = columnDescriptions.get(c).getType();
            TableCell cell = cells.get(c);
            String cellFormattedText = cell.getFormattedValue();
            if (cellFormattedText == null) {
                cellFormattedText = formatters.get(cell.getType()).format(cell.getValue());
            }

            Element tdElement = document.createElement("td");
            if (cell.isNull()) {
                tdElement.setTextContent("\u00a0");
            } else {
                switch (valueType) {
                case NUMBER:
                    tdElement.setAttribute("align", "right");
                    tdElement.setTextContent(cellFormattedText);
                    break;
                case BOOLEAN:
                    BooleanValue booleanValue = (BooleanValue) cell.getValue();
                    tdElement.setAttribute("align", "center");
                    if (booleanValue.getValue()) {
                        tdElement.setTextContent("\u2714"); // Check mark.
                    } else {
                        tdElement.setTextContent("\u2717"); // X mark.
                    }
                    break;
                default:
                    if (StringUtils.isEmpty(cellFormattedText)) {
                        tdElement.setTextContent("\u00a0"); // nbsp.
                    } else {
                        tdElement.setTextContent(cellFormattedText);
                    }
                }
            }
            trElement.appendChild(tdElement);
        }
        tableElement.appendChild(trElement);
    }
    bodyElement.appendChild(tableElement);

    // Warnings:
    for (Warning warning : dataTable.getWarnings()) {
        bodyElement.appendChild(document.createElement("br"));
        bodyElement.appendChild(document.createElement("br"));
        Element messageElement = document.createElement("div");
        messageElement.setTextContent(
                warning.getReasonType().getMessageForReasonType() + ". " + warning.getMessage());
        bodyElement.appendChild(messageElement);
    }

    return transformDocumentToHtmlString(document);
}

From source file:Main.java

public static Element toXML(Color c, Document document) {
    Element result = document.createElement("color");

    String name;/*  w ww  .ja  v  a  2s  .com*/
    if (c.equals(Color.WHITE)) {
        name = "white";
    } else if (c.equals(Color.CYAN)) {
        name = "cyan";
    } else if (c.equals(Color.YELLOW)) {
        name = "yellow";
    } else if (c.equals(Color.PINK)) {
        name = "pink";
    } else if (c.equals(Color.GREEN)) {
        name = "green";
    } else {
        name = "white";
    }

    result.setAttribute("name", name);

    return result;
}

From source file:Main.java

public static Element appendSingleValElementEncoded(Document owner, Element appendElement, String newElemName,
        String newElemVal) {/*from w  w  w  . j av a 2  s  .  com*/
    Element newElem;
    newElem = owner.createElement(newElemName);
    if (newElemVal != null) {
        String encodedVal = "";
        try {
            encodedVal = URLEncoder.encode(newElemVal, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Text value = owner.createTextNode(encodedVal);
        newElem.appendChild(value);
        newElem.setAttribute("enc", "t");
        newElem.setAttribute("charSet", "UTF-8");
    }
    appendElement.appendChild(newElem);
    return (newElem);
}

From source file:com.moviejukebox.tools.DOMHelper.java

/**
 * Append a child element to a parent element with a single attribute/value pair
 *
 * @param doc/* ww w  .  java  2  s .  co m*/
 * @param parentElement
 * @param elementName
 * @param elementValue
 * @param attribName
 * @param attribValue
 */
public static void appendChild(Document doc, Element parentElement, String elementName, String elementValue,
        String attribName, String attribValue) {
    Element child = doc.createElement(elementName);
    Text text = doc.createTextNode(elementValue);
    child.appendChild(text);
    child.setAttribute(attribName, attribValue);
    parentElement.appendChild(child);
}