Example usage for org.w3c.dom Element getAttributes

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

Introduction

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

Prototype

public NamedNodeMap getAttributes();

Source Link

Document

A NamedNodeMap containing the attributes of this node (if it is an Element) or null otherwise.

Usage

From source file:Main.java

protected static String nodeToString(Node node, Set<String> parentPrefixes, String namespaceURI)
        throws Exception {
    StringBuilder b = new StringBuilder();

    if (node == null) {
        return "";
    }/*w  ww  .java  2s  .  co  m*/

    if (node instanceof Element) {
        Element element = (Element) node;
        b.append("<");
        b.append(element.getNodeName());

        Map<String, String> thisLevelPrefixes = new HashMap();
        if (element.getPrefix() != null && !parentPrefixes.contains(element.getPrefix())) {
            thisLevelPrefixes.put(element.getPrefix(), element.getNamespaceURI());
        }

        if (element.hasAttributes()) {
            NamedNodeMap map = element.getAttributes();
            for (int i = 0; i < map.getLength(); i++) {
                Node attr = map.item(i);
                if (attr.getNodeName().startsWith("xmlns"))
                    continue;
                if (attr.getPrefix() != null && !parentPrefixes.contains(attr.getPrefix())) {
                    thisLevelPrefixes.put(attr.getPrefix(), element.getNamespaceURI());
                }
                b.append(" ");
                b.append(attr.getNodeName());
                b.append("=\"");
                b.append(attr.getNodeValue());
                b.append("\"");
            }
        }

        if (namespaceURI != null && !thisLevelPrefixes.containsValue(namespaceURI)
                && !namespaceURI.equals(element.getParentNode().getNamespaceURI())) {
            b.append(" xmlns=\"").append(namespaceURI).append("\"");
        }

        for (Map.Entry<String, String> entry : thisLevelPrefixes.entrySet()) {
            b.append(" xmlns:").append(entry.getKey()).append("=\"").append(entry.getValue()).append("\"");
            parentPrefixes.add(entry.getKey());
        }

        NodeList children = element.getChildNodes();
        boolean hasOnlyAttributes = true;
        for (int i = 0; i < children.getLength(); i++) {
            Node child = children.item(i);
            if (child.getNodeType() != Node.ATTRIBUTE_NODE) {
                hasOnlyAttributes = false;
                break;
            }
        }
        if (!hasOnlyAttributes) {
            b.append(">");
            for (int i = 0; i < children.getLength(); i++) {
                b.append(nodeToString(children.item(i), parentPrefixes, children.item(i).getNamespaceURI()));
            }
            b.append("</");
            b.append(element.getNodeName());
            b.append(">");
        } else {
            b.append("/>");
        }

        for (String thisLevelPrefix : thisLevelPrefixes.keySet()) {
            parentPrefixes.remove(thisLevelPrefix);
        }

    } else if (node.getNodeValue() != null) {
        b.append(encodeText(node.getNodeValue(), node instanceof Attr));
    }

    return b.toString();
}

From source file:Main.java

protected static String nodeToString(Node node, Set<String> parentPrefixes, String namespaceURI)
        throws Exception {
    StringBuilder b = new StringBuilder();

    if (node == null) {
        return "";
    }//from w w w . j  a va  2  s  .  c  o  m

    if (node instanceof Element) {
        Element element = (Element) node;
        b.append("<");
        b.append(element.getNodeName());

        Map<String, String> thisLevelPrefixes = new HashMap();
        if (element.getPrefix() != null && !parentPrefixes.contains(element.getPrefix())) {
            thisLevelPrefixes.put(element.getPrefix(), element.getNamespaceURI());
        }

        if (element.hasAttributes()) {
            NamedNodeMap map = element.getAttributes();
            for (int i = 0; i < map.getLength(); i++) {
                Node attr = map.item(i);
                if (attr.getNodeName().startsWith("xmlns"))
                    continue;
                if (attr.getPrefix() != null && !parentPrefixes.contains(attr.getPrefix())) {
                    thisLevelPrefixes.put(attr.getPrefix(), element.getNamespaceURI());
                }
                b.append(" ");
                b.append(attr.getNodeName());
                b.append("=\"");
                b.append(attr.getNodeValue());
                b.append("\"");
            }
        }

        if (namespaceURI != null && !thisLevelPrefixes.containsValue(namespaceURI)
                && !namespaceURI.equals(element.getParentNode().getNamespaceURI())) {
            b.append(" xmlns=\"").append(namespaceURI).append("\"");
        }

        for (Map.Entry<String, String> entry : thisLevelPrefixes.entrySet()) {
            b.append(" xmlns:").append(entry.getKey()).append("=\"").append(entry.getValue()).append("\"");
            parentPrefixes.add(entry.getKey());
        }

        NodeList children = element.getChildNodes();
        boolean hasOnlyAttributes = true;
        for (int i = 0; i < children.getLength(); i++) {
            Node child = children.item(i);
            if (child.getNodeType() != Node.ATTRIBUTE_NODE) {
                hasOnlyAttributes = false;
                break;
            }
        }
        if (!hasOnlyAttributes) {
            b.append(">");
            for (int i = 0; i < children.getLength(); i++) {
                b.append(nodeToString(children.item(i), parentPrefixes, children.item(i).getNamespaceURI()));
            }
            b.append("</");
            b.append(element.getNodeName());
            b.append(">");
        } else {
            b.append("/>");
        }

        for (String thisLevelPrefix : thisLevelPrefixes.keySet()) {
            parentPrefixes.remove(thisLevelPrefix);
        }

    } else if (node.getNodeValue() != null) {

        b.append(encodeText(node.getNodeValue()));
    }

    return b.toString();
}

From source file:it.delli.mwebc.servlet.MWebCRenderer.java

public static void buildLayout(Element elem, Widget parent, Page page) throws Exception {
    Widget widget = null;/*ww  w .  j a v a  2 s .com*/
    if (elem.getNodeType() == Node.ELEMENT_NODE && elem.getNodeName().equals("Page")) {
        for (int j = 0; j < elem.getAttributes().getLength(); j++) {
            Node attribute = elem.getAttributes().item(j);
            if (!attribute.getNodeName().equals("id")) {
                if (attribute.getNodeName().equals("eventListener")) {
                    log.debug("Setting PageEventListener");
                    try {
                        page.setEventListener(
                                (PageEventListener) Class.forName(attribute.getNodeValue()).newInstance());
                    } catch (Exception e) {
                        log.error("Exception in setting PageEventListener");
                    }
                }
            }
        }
        if (page.getEventListener() == null) {
            log.debug("Setting default PageEventListener");
            page.setEventListener(new PageEventListener() {

                @Override
                public void onLoad(Event event) {
                }

                @Override
                public void onInit(Event event) {
                }

            });
        }
        for (int i = 0; i < elem.getChildNodes().getLength(); i++) {
            Node node = elem.getChildNodes().item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                buildLayout((Element) node, widget, page);
            }
        }
    } else if (elem.getNodeType() == Node.ELEMENT_NODE && elem.getNodeName().equals("PageFragment")) {
        for (int i = 0; i < elem.getChildNodes().getLength(); i++) {
            Node node = elem.getChildNodes().item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                buildLayout((Element) node, parent, page);
            }
        }
    } else {
        Class<?> widgetClass = page.getApplication().getWidgetClass(elem.getNodeName());
        if (widgetClass == null) {
            log.fatal("Exception in getting widget class for widget " + elem.getNodeName());
            throw new Exception();
        } else if (widgetClass.getName().equals("com.dodifferent.applications.commander.widget.DataListItem")) {
            System.out.println();
        }
        CastHelper castHelper = page.getApplication().getCastHelper(widgetClass);

        String id = null;
        for (int j = 0; j < elem.getAttributes().getLength(); j++) {
            Node attribute = elem.getAttributes().item(j);
            if (attribute.getNodeName().equals("id")) {
                id = attribute.getNodeValue();
                break;
            }
        }

        HashMap<String, Object> initParams = new HashMap<String, Object>();
        for (int j = 0; j < elem.getAttributes().getLength(); j++) {
            Node attributeNode = elem.getAttributes().item(j);
            if (!attributeNode.getNodeName().equals("id") && !attributeNode.getNodeName().startsWith("on")) {
                Field fieldAttribute = ReflectionUtils.getAnnotatedField(widgetClass,
                        attributeNode.getNodeName(), WidgetAttribute.class);
                if (fieldAttribute != null) {
                    fieldAttribute.setAccessible(true);
                    Class<?> propertyType = fieldAttribute.getType();
                    //                  Type[] genericTypes = ((ParameterizedType)fieldAttribute.getGenericType()).getActualTypeArguments();
                    initParams.put(attributeNode.getNodeName(),
                            castHelper.toType(attributeNode.getNodeValue(), propertyType));
                } else {
                    log.warn("Warning in updating server widgets attribute. The attribute '"
                            + attributeNode.getNodeName() + "' doesn't exist for widget "
                            + widgetClass.getName());
                }
            }
        }

        try {
            if (id != null && initParams.keySet().size() == 0) {
                Class[] constructorParams = { Page.class, String.class };
                Constructor widgetConstructor = page.getApplication().getWidgetClass(elem.getNodeName())
                        .getConstructor(constructorParams);
                widget = (Widget) widgetConstructor.newInstance(page, id);
            } else if (id != null && initParams.keySet().size() > 0) {
                Class[] constructorParams = { Page.class, String.class, Map.class };
                Constructor widgetConstructor = page.getApplication().getWidgetClass(elem.getNodeName())
                        .getConstructor(constructorParams);
                widget = (Widget) widgetConstructor.newInstance(page, id, initParams);
            } else if (id == null && initParams.keySet().size() == 0) {
                Class[] constructorParams = { Page.class };
                Constructor widgetConstructor = page.getApplication().getWidgetClass(elem.getNodeName())
                        .getConstructor(constructorParams);
                widget = (Widget) widgetConstructor.newInstance(page);
            } else if (id == null && initParams.keySet().size() > 0) {
                Class[] constructorParams = { Page.class, Map.class };
                Constructor widgetConstructor = page.getApplication().getWidgetClass(elem.getNodeName())
                        .getConstructor(constructorParams);
                widget = (Widget) widgetConstructor.newInstance(page, initParams);
            }
        } catch (Exception e) {
            log.error("Exception in constructing widget " + widget.getClass().getName() + " (" + widget.getId()
                    + ")", e);
        }

        if (widget != null) {
            for (int j = 0; j < elem.getAttributes().getLength(); j++) {
                Node attributeNode = elem.getAttributes().item(j);
                if (!attributeNode.getNodeName().equals("id") && attributeNode.getNodeName().startsWith("on")) {
                    String event = attributeNode.getNodeName();
                    try {
                        widget.addEventListener(event, page.getEventListener(), attributeNode.getNodeValue());
                        //                     Method eventMethod = widget.getClass().getMethod("addEventListener", String.class, EventListener.class, String.class);
                        //                     eventMethod.invoke(widget, event, page.getEventListener(), attributeNode.getNodeValue());
                    } catch (Exception e) {
                        log.warn("Warning in registering EventListener for widget "
                                + widget.getClass().getName() + " (" + widget.getId() + ")", e);
                    }
                }
            }
            for (int i = 0; i < elem.getChildNodes().getLength(); i++) {
                Node node = elem.getChildNodes().item(i);
                if (node.getNodeType() == Node.CDATA_SECTION_NODE || node.getNodeType() == Node.TEXT_NODE) {
                    try {
                        String content = node.getNodeValue().replace("\t", "").replace("\n", "").replace("\"",
                                "\\\"");
                        if (!content.equals("")) {
                            //                        Method attributeMethod = widget.getClass().getMethod("addTextContent", String.class);
                            //                        attributeMethod.invoke(widget, content);
                            widget.addTextContent(content);
                        }
                    } catch (Exception e) {
                        log.warn("Warning in setting content for widget " + widget.getClass().getName() + " ("
                                + widget.getId() + ")", e);
                    }
                } else if (node.getNodeType() == Node.ELEMENT_NODE) {
                    buildLayout((Element) node, widget, page);
                }
            }
            widget.setParent(parent);
        }
    }
}

From source file:Main.java

protected static String nodeToString(Node node, Set<String> parentPrefixes, String namespaceURI)
        throws Exception {
    StringBuilder b = new StringBuilder();

    if (node == null) {
        return "";
    }//from   w w  w.jav a 2 s  .c  om

    if (node instanceof Element) {
        Element element = (Element) node;
        b.append("<");
        b.append(element.getNodeName());

        Map<String, String> thisLevelPrefixes = new HashMap();
        if (element.getPrefix() != null && !parentPrefixes.contains(element.getPrefix())) {
            thisLevelPrefixes.put(element.getPrefix(), element.getNamespaceURI());
        }

        if (element.hasAttributes()) {
            NamedNodeMap map = element.getAttributes();
            for (int i = 0; i < map.getLength(); i++) {
                Node attr = map.item(i);
                if (attr.getNodeName().startsWith("xmlns"))
                    continue;
                if (attr.getPrefix() != null && !parentPrefixes.contains(attr.getPrefix())) {
                    thisLevelPrefixes.put(attr.getPrefix(), element.getNamespaceURI());
                }
                b.append(" ");
                b.append(attr.getNodeName());
                b.append("=\"");
                b.append(attr.getNodeValue());
                b.append("\"");
            }
        }

        if (namespaceURI != null && !thisLevelPrefixes.containsValue(namespaceURI)
                && !namespaceURI.equals(element.getParentNode().getNamespaceURI())) {
            b.append(" xmlns=\"").append(namespaceURI).append("\"");
        }

        for (Map.Entry<String, String> entry : thisLevelPrefixes.entrySet()) {
            b.append(" xmlns:").append(entry.getKey()).append("=\"").append(entry.getValue()).append("\"");
            parentPrefixes.add(entry.getKey());
        }

        NodeList children = element.getChildNodes();
        boolean hasOnlyAttributes = true;
        for (int i = 0; i < children.getLength(); i++) {
            Node child = children.item(i);
            if (child.getNodeType() != Node.ATTRIBUTE_NODE) {
                hasOnlyAttributes = false;
                break;
            }
        }
        if (!hasOnlyAttributes) {
            b.append(">");
            for (int i = 0; i < children.getLength(); i++) {
                b.append(nodeToString(children.item(i), parentPrefixes, children.item(i).getNamespaceURI()));
            }
            b.append("</");
            b.append(element.getNodeName());
            b.append(">");
        } else {
            b.append("/>");
        }

        for (String thisLevelPrefix : thisLevelPrefixes.keySet()) {
            parentPrefixes.remove(thisLevelPrefix);
        }

    } else if (node.getNodeValue() != null) {
        b.append(encodeText(node, node.getNodeValue()));
    }

    return b.toString();
}

From source file:kenh.xscript.ScriptUtils.java

/**
 * Debug method for <code>Element</code>
 * @param element/* w w w  .j a va  2  s  .  c o  m*/
 * @param level
 * @param stream
 */
private static final void debug_(Element element, int level, PrintStream stream) {
    String repeatStr = "    ";

    String prefix = StringUtils.repeat(repeatStr, level);
    stream.print(prefix + "<" + element.getClass().getCanonicalName());

    // Attribute output
    Map<String, String> attributes = element.getAttributes();
    if (attributes != null && attributes.size() > 0) {
        Set<String> keys = attributes.keySet();
        for (String key : keys) {
            stream.print(" " + key + "=\"" + attributes.get(key) + "\"");
        }
    }

    Vector<Element> children = element.getChildren();
    String text = element.getText();
    if ((children == null || children.size() == 0) && StringUtils.isBlank(text)) {
        stream.println("/>");
        return;
    } else {
        stream.println(">");

        // child elements
        if (children != null && children.size() > 0) {
            for (Element child : children) {
                debug_(child, level + 1, stream);
            }
        }

        // text/context
        if (StringUtils.isNotBlank(text)) {
            stream.println(prefix + repeatStr + "<![CDATA[" + text + "]]>");
        }

        stream.println(prefix + "</" + element.getClass().getCanonicalName() + ">");
    }
}

From source file:com.hphoto.server.ApiServlet.java

private static void addAttribute(Document doc, Element node, String name, String value) {
    Attr attribute = doc.createAttribute(name);
    attribute.setValue(getLegalXml(value));
    node.getAttributes().setNamedItem(attribute);
}

From source file:DOMTreeTest.java

public static JPanel elementPanel(Element e) {
        JPanel panel = new JPanel();
        panel.add(new JLabel("Element: " + e.getTagName()));
        final NamedNodeMap map = e.getAttributes();
        panel.add(new JTable(new AbstractTableModel() {
            public int getRowCount() {
                return map.getLength();
            }//from  w w w. j  a v  a  2 s  .  c  om

            public int getColumnCount() {
                return 2;
            }

            public Object getValueAt(int r, int c) {
                return c == 0 ? map.item(r).getNodeName() : map.item(r).getNodeValue();
            }
        }));
        return panel;
    }

From source file:Main.java

/**
 * Convert an XML fragment from one namespace to another.
 *
 * @param from      element to translate
 * @param namespace namespace to be translated to
 * @return the element in the new namespace
 *
 * @since 8.4/*  ww w.jav a  2s.  c  o m*/
 */
public static Element translateXML(Element from, String namespace) {
    Element to = from.getOwnerDocument().createElementNS(namespace, from.getLocalName());
    NodeList nl = from.getChildNodes();
    int length = nl.getLength();
    for (int i = 0; i < length; i++) {
        Node node = nl.item(i);
        Node newNode;
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            newNode = translateXML((Element) node, namespace);
        } else {
            newNode = node.cloneNode(true);
        }
        to.appendChild(newNode);
    }
    NamedNodeMap m = from.getAttributes();
    for (int i = 0; i < m.getLength(); i++) {
        Node attr = m.item(i);
        to.setAttribute(attr.getNodeName(), attr.getNodeValue());
    }
    return to;
}

From source file:Main.java

/**
 * Checks whether the expected XML element is contained in the actual
 * element. I.e., every attribute of the expected element must occur in the
 * actual element, with the same value, and all child nodes in the expected
 * element must occur in the actual element; if multiple child nodes with
 * the same name are found in the expected element, the first found
 * identifying attribute in the expected child element is used to identify
 * the child in the actual element.//from w w w.j  a  v a 2  s.  c o m
 * 
 * @param expected
 * @param actual
 * @return
 */
public static void assertContains(Element expected, Element actual, String messagePrefix,
        String... identifyingAttributes) {
    if (!expected.getTagName().equals(actual.getTagName())) {
        throw new AssertionError(messagePrefix + "\nExpected tagname differs from actual tagname (expected '"
                + printNodeOnly(expected) + "', found " + printNodeOnly(actual) + ")");
    }

    // Compare attributes
    NamedNodeMap expectedAttributes = expected.getAttributes();
    for (int i = expectedAttributes.getLength() - 1; i >= 0; i--) {
        String expectedAttributeName = expectedAttributes.item(i).getNodeName();
        String expectedAttributeValue = expectedAttributes.item(i).getNodeValue();

        String actualValue = actual.getAttribute(expectedAttributeName);
        if (actualValue == null || actualValue.isEmpty()) {
            throw new AssertionError(messagePrefix + "\nThe attribute '" + expectedAttributeName
                    + "' with value '" + expectedAttributeValue + "' was not found in the result "
                    + printNodeOnly(actual));
        }
        if (!expectedAttributeValue.equals(actualValue)) {
            throw new AssertionError(messagePrefix + "\nThe attribute '" + expectedAttributeName
                    + "' has value '" + actualValue + "' instead of '" + expectedAttributeValue
                    + "' in the result " + printNodeOnly(actual));
        }
    }

    // Compare child elements
    Node child = expected.getFirstChild();
    while (child != null) {
        if (child instanceof Element) {
            assertContainsChildElement((Element) child, actual, messagePrefix, identifyingAttributes);
        }
        child = child.getNextSibling();
    }
}

From source file:com.msopentech.odatajclient.engine.data.atom.AtomSerializer.java

private static Element entry(final AtomEntry entry) throws ParserConfigurationException {
    final DocumentBuilder builder = ODataConstants.DOC_BUILDER_FACTORY.newDocumentBuilder();
    final Document doc = builder.newDocument();

    final Element entryElem = doc.createElement(ODataConstants.ATOM_ELEM_ENTRY);
    entryElem.setAttribute(XMLConstants.XMLNS_ATTRIBUTE, ODataConstants.NS_ATOM);
    entryElem.setAttribute(ODataConstants.XMLNS_METADATA, ODataConstants.NS_METADATA);
    entryElem.setAttribute(ODataConstants.XMLNS_DATASERVICES, ODataConstants.NS_DATASERVICES);
    entryElem.setAttribute(ODataConstants.XMLNS_GML, ODataConstants.NS_GML);
    entryElem.setAttribute(ODataConstants.XMLNS_GEORSS, ODataConstants.NS_GEORSS);
    if (entry.getBaseURI() != null) {
        entryElem.setAttribute(ODataConstants.ATTR_XMLBASE, entry.getBaseURI().toASCIIString());
    }//  w w  w  . j  av  a2 s  .co m
    doc.appendChild(entryElem);

    final Element category = doc.createElement(ODataConstants.ATOM_ELEM_CATEGORY);
    category.setAttribute(ODataConstants.ATOM_ATTR_TERM, entry.getType());
    category.setAttribute(ODataConstants.ATOM_ATTR_SCHEME, ODataConstants.ATOM_CATEGORY_SCHEME);
    entryElem.appendChild(category);

    if (StringUtils.isNotBlank(entry.getTitle())) {
        final Element title = doc.createElement(ODataConstants.ATOM_ELEM_TITLE);
        title.appendChild(doc.createTextNode(entry.getTitle()));
        entryElem.appendChild(title);
    }

    if (StringUtils.isNotBlank(entry.getSummary())) {
        final Element summary = doc.createElement(ODataConstants.ATOM_ELEM_SUMMARY);
        summary.appendChild(doc.createTextNode(entry.getSummary()));
        entryElem.appendChild(summary);
    }

    setLinks(entryElem, entry.getAssociationLinks());
    setLinks(entryElem, entry.getNavigationLinks());
    setLinks(entryElem, entry.getMediaEditLinks());

    final Element content = doc.createElement(ODataConstants.ATOM_ELEM_CONTENT);
    if (entry.isMediaEntry()) {
        if (StringUtils.isNotBlank(entry.getMediaContentType())) {
            content.setAttribute(ODataConstants.ATTR_TYPE, entry.getMediaContentType());
        }
        if (StringUtils.isNotBlank(entry.getMediaContentSource())) {
            content.setAttribute(ODataConstants.ATOM_ATTR_SRC, entry.getMediaContentSource());
        }
        if (content.getAttributes().getLength() > 0) {
            entryElem.appendChild(content);
        }

        if (entry.getMediaEntryProperties() != null) {
            entryElem.appendChild(doc.importNode(entry.getMediaEntryProperties(), true));
        }
    } else {
        content.setAttribute(ODataConstants.ATTR_TYPE, ContentType.APPLICATION_XML.getMimeType());
        if (entry.getContent() != null) {
            content.appendChild(doc.importNode(entry.getContent(), true));
        }
        entryElem.appendChild(content);
    }

    return entryElem;
}