Example usage for org.w3c.dom Element getAttribute

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

Introduction

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

Prototype

public String getAttribute(String name);

Source Link

Document

Retrieves an attribute value by name.

Usage

From source file:com.googlecode.jgenhtml.JGenHtmlTest.java

/**
 * Get elements which match the tagName and className specified.
 * @param document The document which contains the elements we are looking for.
 * @param tagName The tag name of the elements to match.
 * @param className The CSS class to match. If null will return all elements that match the tagName alone.
 * @return A collection of matching elements.
 */// ww  w  . j  ava 2  s .c  om
private static List<Element> getElementsByTagAndClass(Document document, String tagName, String className) {
    NodeList candidates = document.getElementsByTagName(tagName);
    List<Element> result = new ArrayList<Element>();
    for (int i = 0; i < candidates.getLength(); i++) {
        Element next = (Element) candidates.item(i);
        if (className == null || className.equals(next.getAttribute("class")))//todo find a space separated list
        {
            result.add(next);
        }
    }
    return result;
}

From source file:com.impetus.kundera.loader.PersistenceXMLLoader.java

/**
 * Validates an xml object graph against its schema. Therefore it reads the
 * version from the root tag and tries to load the related xsd file from the
 * classpath.// w w w  .  ja  v a2  s  .  c o m
 * 
 * @param xmlRootNode
 *            root xml node of the document to validate
 * @throws InvalidConfigurationException
 *             if the validation could not be performed or the xml graph is
 *             invalid against the schema
 */
private static void validateDocumentAgainstSchema(final Document xmlRootNode)
        throws InvalidConfigurationException {
    final Element rootElement = xmlRootNode.getDocumentElement();
    final String version = rootElement.getAttribute("version");
    String schemaFileName = "persistence_" + version.replace(".", "_") + ".xsd";

    try {
        final List validationErrors = new ArrayList();
        final String schemaLanguage = XMLConstants.W3C_XML_SCHEMA_NS_URI;
        final StreamSource streamSource = new StreamSource(getStreamFromClasspath(schemaFileName));
        final Schema schemaDefinition = SchemaFactory.newInstance(schemaLanguage).newSchema(streamSource);

        final Validator schemaValidator = schemaDefinition.newValidator();
        schemaValidator.setErrorHandler(new ErrorLogger("XML InputStream", validationErrors));
        schemaValidator.validate(new DOMSource(xmlRootNode));

        if (!validationErrors.isEmpty()) {
            final String exceptionText = "persistence.xml is not conform against the supported schema definitions.";
            throw new InvalidConfigurationException(exceptionText);
        }
    } catch (SAXException e) {
        final String exceptionText = "Error validating persistence.xml against schema defintion, caused by: ";
        throw new InvalidConfigurationException(exceptionText, e);
    } catch (IOException e) {
        final String exceptionText = "Error opening xsd schema file. The given persistence.xml descriptor version "
                + version + " might not be supported yet.";
        throw new InvalidConfigurationException(exceptionText, e);
    }
}

From source file:org.dataone.proto.trove.mn.http.client.HttpExceptionHandler.java

private static ErrorElements deserializeXml(HttpResponse response) throws IllegalStateException, IOException //    throws NotFound, InvalidToken, ServiceFailure, NotAuthorized,
//    NotFound, IdentifierNotUnique, UnsupportedType,
//    InsufficientResources, InvalidSystemMetadata, NotImplemented,
//    InvalidCredentials, InvalidRequest, IOException {
{
    ErrorElements ee = new ErrorElements();

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    Document doc;//from   w w  w .j  a  va2 s.  co m

    int httpCode = response.getStatusLine().getStatusCode();
    if (response.getEntity() != null) {
        BufferedInputStream bErrorStream = new BufferedInputStream(response.getEntity().getContent());
        bErrorStream.mark(5000); // good for resetting up to 5000 bytes

        String detailCode = null;
        String description = null;
        String name = null;
        int errorCode = -1;
        try {
            DocumentBuilder db = dbf.newDocumentBuilder();
            doc = db.parse(bErrorStream);
            Element root = doc.getDocumentElement();
            root.normalize();
            if (root.getNodeName().equalsIgnoreCase("error")) {
                if (root.hasAttribute("errorCode")) {
                    try {
                        errorCode = Integer.getInteger(root.getAttribute("errorCode"));
                    } catch (NumberFormatException nfe) {
                        System.out.println("errorCode unexpectedly not able to parse to int,"
                                + " using http status for creating exception");
                        errorCode = httpCode;
                    }
                }
                if (errorCode != httpCode) //            throw new ServiceFailure("1000","errorCode in message body doesn't match httpStatus");
                {
                    System.out.println("errorCode in message body doesn't match httpStatus,"
                            + " using errorCode for creating exception");
                }
                if (root.hasAttribute("detailCode")) {
                    detailCode = root.getAttribute("detailCode");
                } else {
                    detailCode = "detail code is Not Set!";
                }
                if (root.hasAttribute("name")) {
                    name = root.getAttribute("name");
                } else {
                    name = "Exception";
                }
                Node child = root.getFirstChild();
                do {
                    if (child.getNodeType() == Node.ELEMENT_NODE) {
                        if (child.getNodeName().equalsIgnoreCase("description")) {
                            Element element = (Element) child;
                            description = element.getTextContent();
                            break;
                        }
                    }
                } while ((child = child.getNextSibling()) != null);
            } else {
                description = domToString(doc);
                detailCode = "detail code was never Set!";
            }
        } catch (TransformerException e) {
            description = deserializeNonXMLErrorStream(bErrorStream, e);
        } catch (SAXException e) {
            description = deserializeNonXMLErrorStream(bErrorStream, e);
        } catch (IOException e) {
            description = deserializeNonXMLErrorStream(bErrorStream, e);
        } catch (ParserConfigurationException e) {
            description = deserializeNonXMLErrorStream(bErrorStream, e);
        }

        ee.setCode(errorCode);
        ee.setName(name);
        ee.setDetailCode(detailCode);
        ee.setDescription(description);
    }
    return ee;
}

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

/**
 * returns the value of a state attribute
 *
 * @param state         the betterForm state element to examine
 * @param attributeName the name of the attribute to look up
 * @return the value of a state attribute
 *//*from  w w  w  .  j  a  v  a2  s .co  m*/
public static Object getStateAttribute(Element state, String attributeName) {
    if (state.hasAttribute(attributeName)) {
        return state.getAttribute(attributeName);
    }
    return null;
}

From source file:cz.incad.kramerius.rest.api.k5.client.search.SearchResource.java

public static void changeMasterPidInDOM(Element docElem) {
    // <str name="PID">uuid:2ad31d65-50ca-11e1-916e-001b63bd97ba</str>
    Element elm = XMLUtils.findElement(docElem, new XMLUtils.ElementsFilter() {

        @Override/*  w ww. j  av  a  2  s.co m*/
        public boolean acceptElement(Element element) {
            if (element.getNodeName().equals("str")) {
                if (element.hasAttribute("name") && (element.getAttribute("name").equals("PID"))) {
                    return true;
                }
            }
            return false;
        }
    });
    if (elm != null) {
        String pid = elm.getTextContent();
        if (pid.contains("/")) {
            pid = pid.replace("/", "");
            elm.setTextContent(pid);
        }
    }
}

From source file:com.vmware.qe.framework.datadriven.utils.XMLUtil.java

/**
 * Get child nodes of the first element that has the specified tag name and also contains the
 * specified attribute id and value/* w ww .  java  2s .c o  m*/
 * 
 * @param xmlFile XML file contents
 * @param elementName name of the required element
 * @param attrId Id of an attribute in element
 * @param attrVal attribute value for the given attribute
 * @return NodeList childNodes if the given element name with the given attributeId and
 *         attributeValue exists, otherwise null
 * @throws Exception
 */
public static NodeList getChildNodes(String xmlFile, String elementName, String attrId, String attrVal)
        throws Exception {
    NodeList childNodes = null;
    Document xmlDoc = getXmlDocumentElement(xmlFile);
    NodeList elements = xmlDoc.getElementsByTagName(elementName);
    for (int i = 0; i < elements.getLength(); i++) {
        Element element = (Element) elements.item(i);
        if (element.hasAttribute(attrId)) {
            if (element.getAttribute(attrId).equals(attrVal)) {
                childNodes = element.getChildNodes();
                break;
            }
        }
    }
    return childNodes;
}

From source file:es.juntadeandalucia.panelGestion.negocio.utiles.PanelSettings.java

/**
 * TODO// w  w  w .ja  v  a2s .  c om
 *
 * @param slaveNode
 * @return
 */
private static GeosearchInstanceVO readGeosearchNode(Node geosearchNode) {
    GeosearchInstanceVO instanceVO = null;
    if (geosearchNode.getNodeType() == Node.ELEMENT_NODE) {
        Element geosearchlem = ((Element) geosearchNode);
        String url = geosearchlem.getAttribute("url");
        url = Utils.removeLastSlash(url);
        String user = geosearchlem.getAttribute("user");
        String password = geosearchlem.getAttribute("password");
        String srs = geosearchlem.getAttribute("srs");

        instanceVO = new GeosearchInstanceVO();
        instanceVO.setUrl(url);
        instanceVO.setUser(user);
        instanceVO.setPassword(password);
        instanceVO.setSRS(srs);
    }
    return instanceVO;
}

From source file:org.shareok.data.documentProcessor.DocumentProcessorUtil.java

/**
 *
 * @param filePath : file path/*from   ww w  . j a v a  2  s .  com*/
 * @param tagName : tag name
 * @param attributeMap : the map of attribute name-value map. Note: no null value contained in this map
 * @return : value of the elements
 */
public static String[] getDataFromXmlByTagNameAndAttributes(String filePath, String tagName,
        Map<String, String> attributeMap) {
    String[] data = null;
    try {
        File file = new File(filePath);

        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(file);
        doc.getDocumentElement().normalize();

        NodeList nList = doc.getElementsByTagName(tagName);

        int length = nList.getLength();

        if (length == 0) {
            return null;
        }

        List<String> dataList = new ArrayList<>();
        for (int temp = 0; temp < length; temp++) {
            Node nNode = nList.item(temp);
            if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                boolean attrMatched = true;
                Element eElement = (Element) nNode;
                for (String att : attributeMap.keySet()) {
                    String val = attributeMap.get(att);
                    if (!eElement.hasAttribute(att) || !val.equals(eElement.getAttribute(att))) {
                        attrMatched = false;
                    }
                }
                if (attrMatched == true) {
                    dataList.add(eElement.getTextContent());
                }
            }
        }

        int size = dataList.size();
        data = new String[size];
        data = dataList.toArray(data);

    } catch (ParserConfigurationException | SAXException | IOException | DOMException ex) {
        logger.error("Cannot get the data from file at " + filePath + " by tag name " + tagName
                + " and attributes map", ex);
    }
    return data;
}

From source file:edu.indiana.lib.twinpeaks.search.SearchSource.java

/**
 * Set a global parameter from the configuration file
 * @param name Parameter name//from  w  w  w .  j  a v  a 2s  .  c o  m
 */
private static void setGlobalConfiguationValue(Document document, String name) {
    Element element;

    element = DomUtils.getElement(document.getDocumentElement(), name);
    if (element != null) {
        String text = element.getAttribute("name");

        if (!StringUtils.isNull(text)) {
            _globalMap.put(name, text);
        }
    }
}

From source file:com.icesoft.faces.util.CoreUtils.java

public static void addPanelTooltip(FacesContext facesContext, UIComponent uiComponent) {
    DOMContext domContext = DOMContext.getDOMContext(facesContext, uiComponent);
    if (uiComponent.getAttributes().get("panelTooltip") == null)
        return;/*from   www .  j a  v  a  2  s  .  co  m*/
    String panelTooltipId = String.valueOf(uiComponent.getAttributes().get("panelTooltip"));
    int delay = 500;
    String hideOn = "mouseout";
    boolean dynamic = false;
    String formId = "";
    String ctxValue = "";
    String displayOn = "hover";
    boolean moveWithMouse = false;

    //TODO: convert to :: utility findComponent
    //            UIComponent panelTooltip = D2DViewHandler.findComponent(panelTooltipId, uiComponent);
    //            UIComponent panelTooltip = facesContext.getViewRoot().findComponent(panelTooltipId);
    UIComponent panelTooltip = CoreComponentUtils.findComponent(panelTooltipId, uiComponent);
    if (panelTooltip != null/* && family type equals panelPopup*/) {
        //replace the id with the clientid
        panelTooltipId = panelTooltip.getClientId(facesContext);
        if (panelTooltip.getAttributes().get("hideOn") != null) {
            hideOn = String.valueOf(panelTooltip.getAttributes().get("hideOn"));
        }
        if (panelTooltip.getAttributes().get("dynamic") != null) {
            dynamic = ((Boolean) panelTooltip.getAttributes().get("dynamic")).booleanValue();
        }
        if (panelTooltip.getAttributes().get("hoverDelay") != null) {
            delay = new Integer(String.valueOf(panelTooltip.getAttributes().get("hoverDelay"))).intValue();
        }
        if (uiComponent.getAttributes().get("contextValue") != null) {
            ctxValue = String.valueOf(uiComponent.getAttributes().get("contextValue"));
        }
        if (panelTooltip.getAttributes().get("displayOn") != null) {
            displayOn = String.valueOf(panelTooltip.getAttributes().get("displayOn"));
        }
        if (panelTooltip.getAttributes().get("moveWithMouse") != null) {
            moveWithMouse = ((Boolean) panelTooltip.getAttributes().get("moveWithMouse")).booleanValue();
        }
    }
    UIComponent form = DomBasicRenderer.findForm(panelTooltip);
    if (form != null) {
        formId = form.getClientId(facesContext);
    }

    Element rootElement = (Element) domContext.getRootNode();
    String onAttr, onValue;
    if (displayOn.equals("click") || displayOn.equals("dblclick")) {
        onAttr = "on" + displayOn;
    } else if (displayOn.equals("altclick")) {
        onAttr = "oncontextmenu";
    } else {
        onAttr = "onmouseover";
    }
    onValue = String.valueOf(rootElement.getAttribute(onAttr));
    onValue += "; new ToolTipPanelPopup(this, '" + panelTooltipId + "', event, '" + hideOn + "','" + delay
            + "', '" + dynamic + "', '" + formId + "', '" + ctxValue + "','"
            + CoreUtils.resolveResourceURL(facesContext, "/xmlhttp/blank") + "','" + displayOn + "',"
            + moveWithMouse + ");";
    rootElement.setAttribute(onAttr, onValue);
}