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:org.infoscoop.service.SiteAggregationMenuService.java

private static void setElement2Buf(Element xml, StringBuffer buf) {
    buf.append("<").append(xml.getNodeName());
    NamedNodeMap attrs = xml.getAttributes();
    for (int i = 0; i < attrs.getLength(); i++) {
        Attr attr = (Attr) attrs.item(i);
        buf.append(" ").append(attr.getName()).append("=\"").append(XmlUtil.escapeXmlEntities(attr.getValue()))
                .append("\"");
    }/* ww w . j  av  a 2 s  .  c o m*/
    if (xml.hasChildNodes()) {
        buf.append(">").append(XmlUtil.escapeXmlEntities(xml.getFirstChild().getNodeValue())).append("</")
                .append(xml.getNodeName()).append(">");
    } else {
        buf.append("/>\n");
    }
}

From source file:org.infoscoop.util.Xml2Json.java

private Object node2json(Element element) throws Exception {
    Map map = new SequencedHashMap();
    String xpath = getXPath(element);
    if (singles.contains(xpath)) {
        if (element.getFirstChild() != null)
            return listner.text(element.getFirstChild().getNodeValue());
        else/*from  www .j  av a  2 s.c o  m*/
            return "";
    }
    NamedNodeMap attrs = element.getAttributes();
    for (int i = 0; i < attrs.getLength(); i++) {
        Node attr = attrs.item(i);
        String name = attr.getNodeName();
        String value = attr.getNodeValue();
        map.put(name, listner.text(value));
    }
    NodeList childs = element.getChildNodes();
    nodelist2json(map, childs);
    return new JSONObject(map);
}

From source file:org.intellij.xquery.runner.rt.vendor.exist.ExistRunnerApp.java

private String getEvaluationResult(String response)
        throws ParserConfigurationException, SAXException, IOException, XPathExpressionException,
        TransformerException, IllegalAccessException, ClassNotFoundException, InstantiationException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(false);/*from  w  w  w  .  j  ava 2 s  .com*/
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(new InputSource(new StringReader(response)));
    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();
    XPathExpression expr = xpath.compile("/result/value/text()");
    String textValue = expr.evaluate(doc);
    if (!"".equals(textValue))
        return textValue;
    expr = xpath.compile("/result/text()");
    String resultingXmlAsText = expr.evaluate(doc);
    if (!"".equals(resultingXmlAsText.trim()))
        return resultingXmlAsText;
    expr = xpath.compile("/result/child::*");
    Element node = (Element) expr.evaluate(doc, NODE);
    if (node != null) {
        NamedNodeMap attributes = node.getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
            Node attribute = attributes.item(i);
            String nodeName = attribute.getNodeName();
            String nodeValue = attribute.getNodeValue();
            if (XMLNS.equals(nodeName) && SERIALIZED_NAMESPACE.equals(nodeValue)) {
                node.removeAttribute(XMLNS);
            }
        }
        return prettyPrint(node, builder.getDOMImplementation());
    } else {
        return response;
    }
}

From source file:org.jasig.portal.layout.dlm.RDBMDistributedLayoutStore.java

@Override
protected Element getStructure(Document doc, LayoutStructure ls) {
    Element structure = null;//  w w w.j a  v  a 2 s  .  co  m

    // handle migration of legacy namespace
    String type = ls.getType();
    if (type != null && type.startsWith(Constants.LEGACY_NS)) {
        type = Constants.NS + type.substring(Constants.LEGACY_NS.length());
    }

    if (ls.isChannel()) {
        final IPortletDefinition channelDef = this.portletDefinitionRegistry
                .getPortletDefinition(String.valueOf(ls.getChanId()));
        if (channelDef != null && channelApproved(channelDef.getApprovalDate())) {
            structure = this.getElementForChannel(doc, channelPrefix + ls.getStructId(), channelDef,
                    ls.getLocale());
        } else {
            // Create an error channel if channel is missing or not approved
            String missingChannel = "Unknown";
            if (channelDef != null) {
                missingChannel = channelDef.getName();
            }
            structure = this.getElementForChannel(doc, channelPrefix + ls.getStructId(),
                    MissingPortletDefinition.INSTANCE, null);
            //        structure = MissingPortletDefinition.INSTANCE.getDocument(doc, channelPrefix + ls.getStructId());
            //        structure = MissingPortletDefinition.INSTANCE.getDocument(doc, channelPrefix + ls.getStructId(),
            //                "The '" + missingChannel + "' channel is no longer available. " +
            //                "Please remove it from your layout.",
            //                -1);
        }
    } else {
        // create folder objects including dlm new types in cp namespace
        if (type != null && type.startsWith(Constants.NS)) {
            structure = doc.createElementNS(Constants.NS_URI, type);
        } else {
            structure = doc.createElement("folder");
        }
        structure.setAttribute("name", ls.getName());
        structure.setAttribute("type", (type != null ? type : "regular"));
    }

    structure.setAttribute("hidden", (ls.isHidden() ? "true" : "false"));
    structure.setAttribute("immutable", (ls.isImmutable() ? "true" : "false"));
    structure.setAttribute("unremovable", (ls.isUnremovable() ? "true" : "false"));
    if (localeAware) {
        structure.setAttribute("locale", ls.getLocale()); // for i18n by Shoji
    }

    /*
     * Parameters from up_layout_param are loaded slightly differently for
     * folders and channels. For folders all parameters are added as attributes
     * of the Element. For channels only those parameters with names starting
     * with the dlm namespace Constants.NS are added as attributes to the Element.
     * Others are added as child parameter Elements.
     */
    if (ls.getParameters() != null) {
        for (final Iterator itr = ls.getParameters().iterator(); itr.hasNext();) {
            final StructureParameter sp = (StructureParameter) itr.next();
            String pName = sp.getName();

            // handle migration of legacy namespace
            if (pName.startsWith(Constants.LEGACY_NS)) {
                pName = Constants.NS + sp.getName().substring(Constants.LEGACY_NS.length());
            }

            if (!ls.isChannel()) { // Folder
                if (pName.startsWith(Constants.NS)) {
                    structure.setAttributeNS(Constants.NS_URI, pName, sp.getValue());
                } else {
                    structure.setAttribute(pName, sp.getValue());
                }
            } else // Channel
            {
                // if dealing with a dlm namespace param add as attribute
                if (pName.startsWith(Constants.NS)) {
                    structure.setAttributeNS(Constants.NS_URI, pName, sp.getValue());
                    itr.remove();
                } else {
                    /*
                     * do traditional override processing. some explanation is in
                     * order. The structure element was created by the
                     * ChannelDefinition and only contains parameter children if the
                     * definition had defined parameters. These are checked for each
                     * layout loaded parameter as found in LayoutStructure.parameters.
                     * If a name match is found then we need to see if overriding is
                     * allowed and if so we set the value on the child parameter
                     * element. At that point we are done with that version loaded
                     * from the layout so we remove it from the in-memory set of
                     * parameters that are being merged-in. Then, after all such have
                     * been checked against those added by the channel definition we
                     * add in any remaining as adhoc, unregulated parameters.
                     */
                    final NodeList nodeListParameters = structure.getElementsByTagName("parameter");
                    for (int j = 0; j < nodeListParameters.getLength(); j++) {
                        final Element parmElement = (Element) nodeListParameters.item(j);
                        final NamedNodeMap nm = parmElement.getAttributes();

                        final String nodeName = nm.getNamedItem("name").getNodeValue();
                        if (nodeName.equals(pName)) {
                            final Node override = nm.getNamedItem("override");
                            if (override != null && override.getNodeValue().equals("yes")) {
                                final Node valueNode = nm.getNamedItem("value");
                                valueNode.setNodeValue(sp.getValue());
                            }
                            itr.remove();
                            break; // found the corresponding one so skip the rest
                        }
                    }
                }
            }
        }
        // For channels, add any remaining parameter elements loaded with the
        // layout as adhoc, unregulated, parameter children that can be overridden.
        if (ls.isChannel()) {
            for (final Iterator itr = ls.getParameters().iterator(); itr.hasNext();) {
                final StructureParameter sp = (StructureParameter) itr.next();
                final Element parameter = doc.createElement("parameter");
                parameter.setAttribute("name", sp.getName());
                parameter.setAttribute("value", sp.getValue());
                parameter.setAttribute("override", "yes");
                structure.appendChild(parameter);
            }
        }
    }
    // finish setting up elements based on loaded params
    final String origin = structure.getAttribute(Constants.ATT_ORIGIN);
    final String prefix = ls.isChannel() ? channelPrefix : folderPrefix;

    // if not null we are dealing with a node incorporated from another
    // layout and this node contains changes made by the user so handle
    // id swapping.
    if (!origin.equals("")) {
        structure.setAttributeNS(Constants.NS_URI, Constants.ATT_PLF_ID, prefix + ls.getStructId());
        structure.setAttribute("ID", origin);
    } else if (!ls.isChannel())
    // regular folder owned by this user, need to check if this is a
    // directive or ui element. If the latter then use traditional id
    // structure
    {
        if (type != null && type.startsWith(Constants.NS)) {
            structure.setAttribute("ID", Constants.DIRECTIVE_PREFIX + ls.getStructId());
        } else {
            structure.setAttribute("ID", folderPrefix + ls.getStructId());
        }
    } else {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Adding identifier " + folderPrefix + ls.getStructId());
        }
        structure.setAttribute("ID", channelPrefix + ls.getStructId());
    }
    structure.setIdAttribute(Constants.ATT_ID, true);
    return structure;
}

From source file:org.jasig.portal.layout.dlm.RDBMDistributedLayoutStore.java

@Override
protected int saveStructure(Node node, PreparedStatement structStmt, PreparedStatement parmStmt)
        throws SQLException {
    if (node == null) { // No more
        return 0;
    }//w ww . j  av  a2 s .  c  o m
    if (node.getNodeName().equals("parameter")) {
        //parameter, skip it and go on to the next node
        return this.saveStructure(node.getNextSibling(), structStmt, parmStmt);
    }
    if (!(node instanceof Element)) {
        return 0;
    }

    final Element structure = (Element) node;

    if (LOG.isDebugEnabled()) {
        LOG.debug("saveStructure XML content: " + XmlUtilitiesImpl.toString(node));
    }

    // determine the struct_id for storing in the db. For incorporated nodes in
    // the plf their ID is a system-wide unique ID while their struct_id for
    // storing in the db is cached in a dlm:plfID attribute.
    int saveStructId = -1;
    final String plfID = structure.getAttribute(Constants.ATT_PLF_ID);

    if (!plfID.equals("")) {
        saveStructId = Integer.parseInt(plfID.substring(1));
    } else {
        final String id = structure.getAttribute("ID");
        saveStructId = Integer.parseInt(id.substring(1));
    }

    int nextStructId = 0;
    int childStructId = 0;
    int chanId = -1;
    IPortletDefinition portletDef = null;
    final boolean isChannel = node.getNodeName().equals("channel");

    if (isChannel) {
        chanId = Integer.parseInt(node.getAttributes().getNamedItem("chanID").getNodeValue());
        portletDef = this.portletDefinitionRegistry.getPortletDefinition(String.valueOf(chanId));
        if (portletDef == null) {
            //Portlet doesn't exist any more, drop the layout node
            return 0;
        }
    }

    if (node.hasChildNodes()) {
        childStructId = this.saveStructure(node.getFirstChild(), structStmt, parmStmt);
    }
    nextStructId = this.saveStructure(node.getNextSibling(), structStmt, parmStmt);
    structStmt.clearParameters();
    structStmt.setInt(1, saveStructId);
    structStmt.setInt(2, nextStructId);
    structStmt.setInt(3, childStructId);

    final String externalId = structure.getAttribute("external_id");
    if (externalId != null && externalId.trim().length() > 0) {
        final Integer eID = new Integer(externalId);
        structStmt.setInt(4, eID.intValue());
    } else {
        structStmt.setNull(4, java.sql.Types.NUMERIC);

    }
    if (isChannel) {
        structStmt.setInt(5, chanId);
        structStmt.setNull(6, java.sql.Types.VARCHAR);
    } else {
        structStmt.setNull(5, java.sql.Types.NUMERIC);
        structStmt.setString(6, structure.getAttribute("name"));
    }
    final String structType = structure.getAttribute("type");
    structStmt.setString(7, structType);
    structStmt.setString(8, RDBMServices.dbFlag(xmlBool(structure.getAttribute("hidden"))));
    structStmt.setString(9, RDBMServices.dbFlag(xmlBool(structure.getAttribute("immutable"))));
    structStmt.setString(10, RDBMServices.dbFlag(xmlBool(structure.getAttribute("unremovable"))));
    if (LOG.isDebugEnabled()) {
        LOG.debug(structStmt.toString());
    }
    structStmt.executeUpdate();

    // code to persist extension attributes for dlm
    final NamedNodeMap attribs = node.getAttributes();
    for (int i = 0; i < attribs.getLength(); i++) {
        final Node attrib = attribs.item(i);
        final String name = attrib.getNodeName();

        if (name.startsWith(Constants.NS) && !name.equals(Constants.ATT_PLF_ID)
                && !name.equals(Constants.ATT_FRAGMENT) && !name.equals(Constants.ATT_PRECEDENCE)) {
            // a cp extension attribute. Push into param table.
            parmStmt.clearParameters();
            parmStmt.setInt(1, saveStructId);
            parmStmt.setString(2, name);
            parmStmt.setString(3, attrib.getNodeValue());
            if (LOG.isDebugEnabled()) {
                LOG.debug(parmStmt.toString());
            }
            parmStmt.executeUpdate();
        }
    }
    final NodeList parameters = node.getChildNodes();
    if (parameters != null && isChannel) {
        for (int i = 0; i < parameters.getLength(); i++) {
            if (parameters.item(i).getNodeName().equals("parameter")) {
                final Element parmElement = (Element) parameters.item(i);
                final NamedNodeMap nm = parmElement.getAttributes();
                final String parmName = nm.getNamedItem("name").getNodeValue();
                final String parmValue = nm.getNamedItem("value").getNodeValue();
                final Node override = nm.getNamedItem("override");

                // if no override specified then default to allowed
                if (override != null && !override.getNodeValue().equals("yes")) {
                    // can't override
                } else {
                    // override only for adhoc or if diff from chan def
                    final IPortletDefinitionParameter cp = portletDef.getParameter(parmName);
                    if (cp == null || !cp.getValue().equals(parmValue)) {
                        parmStmt.clearParameters();
                        parmStmt.setInt(1, saveStructId);
                        parmStmt.setString(2, parmName);
                        parmStmt.setString(3, parmValue);
                        if (LOG.isDebugEnabled()) {
                            LOG.debug(parmStmt);
                        }
                        parmStmt.executeUpdate();
                    }
                }
            }
        }
    }
    return saveStructId;
}

From source file:org.jboss.bpm.console.server.util.DOMUtils.java

/** Get the attributes as Map<QName, String>
 */// w w  w. jav  a 2  s  .  c  o  m
public static Map getAttributes(Element el) {
    Map attmap = new HashMap();
    NamedNodeMap attribs = el.getAttributes();
    for (int i = 0; i < attribs.getLength(); i++) {
        Attr attr = (Attr) attribs.item(i);
        String name = attr.getName();
        QName qname = resolveQName(el, name);
        String value = attr.getNodeValue();
        attmap.put(qname, value);
    }
    return attmap;
}

From source file:org.jboss.bpm.console.server.util.DOMUtils.java

/** Copy attributes between elements
 *///from w  w w. j av a 2  s  . c om
public static void copyAttributes(Element destElement, Element srcElement) {
    NamedNodeMap attribs = srcElement.getAttributes();
    for (int i = 0; i < attribs.getLength(); i++) {
        Attr attr = (Attr) attribs.item(i);
        String uri = attr.getNamespaceURI();
        String qname = attr.getName();
        String value = attr.getNodeValue();

        // Prevent DOMException: NAMESPACE_ERR: An attempt is made to create or
        // change an object in a way which is incorrect with regard to namespaces.
        if (uri == null && qname.startsWith("xmlns")) {
            log.trace("Ignore attribute: [uri=" + uri + ",qname=" + qname + ",value=" + value + "]");
        } else {
            destElement.setAttributeNS(uri, qname, value);
        }
    }
}

From source file:org.jboss.jaxr.juddi.transport.SaajTransport.java

private SOAPMessage createSOAPMessage(Element elem) throws Exception {
    String prefix = "uddi";
    MessageFactory msgFactory = MessageFactory.newInstance();
    SOAPFactory factory = SOAPFactory.newInstance();

    SOAPMessage message = msgFactory.createMessage();
    message.getSOAPHeader().detachNode();
    SOAPPart soapPart = message.getSOAPPart();
    SOAPBody soapBody = soapPart.getEnvelope().getBody();
    //Create the outer body element
    String uddins = IRegistry.UDDI_V2_NAMESPACE;
    Name bodyName = factory.createName(elem.getNodeName(), prefix, uddins);
    SOAPBodyElement bodyElement = soapBody.addBodyElement(bodyName);
    bodyElement.addNamespaceDeclaration(prefix, uddins);
    appendAttributes(bodyElement, elem.getAttributes(), factory);
    appendElements(bodyElement, elem.getChildNodes(), factory);
    return message;
}

From source file:org.jboss.jaxr.juddi.transport.SaajTransport.java

private void appendElements(SOAPElement bodyElement, NodeList nlist, SOAPFactory factory) throws SOAPException {
    String prefix = "uddi";
    String uddins = IRegistry.UDDI_V2_NAMESPACE;
    int len = nlist != null ? nlist.getLength() : 0;

    for (int i = 0; i < len; i++) {
        Node node = nlist.item(i);
        short nodeType = node != null ? node.getNodeType() : -100;
        if (Node.ELEMENT_NODE == nodeType) {
            Element el = (Element) node;
            Name name = factory.createName(el.getNodeName(), prefix, uddins);
            SOAPElement attachedEl = bodyElement.addChildElement(name);
            appendAttributes(attachedEl, el.getAttributes(), factory);
            appendElements(attachedEl, el.getChildNodes(), factory);
        } else if (nodeType == Node.TEXT_NODE) {
            bodyElement.addTextNode(node.getNodeValue());
        }//from  w  ww .j  a v  a  2s .c  om
    }
}

From source file:org.jboss.jaxr.juddi.transport.WS4EESaajTransport.java

private SOAPElement getSOAPElement(SOAPBody soapBody, Element elem) {
    String xmlns = IRegistry.UDDI_V2_NAMESPACE;
    SOAPElement soapElement = null;
    SOAPFactory factory = null;//from ww  w.j  a v a2s  .  c  o m
    try {
        factory = SOAPFactory.newInstance();
        //Go through the element
        String name = elem.getNodeName();
        String nsuri = elem.getNamespaceURI();
        if (nsuri == null)
            nsuri = xmlns;
        soapElement = factory.createElement(name, "ns1", nsuri);
        //Get Attributes
        if (elem.hasAttributes()) {
            NamedNodeMap nnm = elem.getAttributes();
            int len = nnm != null ? nnm.getLength() : 0;
            for (int i = 0; i < len; i++) {
                Node n = nnm.item(i);
                String nodename = n.getNodeName();
                String nodevalue = n.getNodeValue();
                soapElement.addAttribute(factory.createName(nodename), nodevalue);
            }
        } else {
            soapElement.addAttribute(factory.createName("xmlns:ns1"), nsuri);
        }

        NodeList nlist = elem.getChildNodes();
        int len = nlist != null ? nlist.getLength() : 0;

        for (int i = 0; i < len; i++) {
            Node node = nlist.item(i);
            short nodeType = node != null ? node.getNodeType() : -100;
            if (Node.ELEMENT_NODE == nodeType) {
                soapElement.addChildElement(getSOAPElement(soapBody, (Element) node));
            } else if (nodeType == Node.TEXT_NODE) {
                soapElement.addTextNode(node.getNodeValue());
            }

        }
    } catch (SOAPException e) {
        e.printStackTrace();
    }
    return soapElement;
}