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.msopentech.odatajclient.engine.data.ODataBinder.java

/**
 * Gets an <tt>ODataProperty</tt> from the given DOM element.
 *
 * @param property content.//w w  w. j a v a  2 s .co m
 * @return <tt>ODataProperty</tt> object.
 */
public static ODataProperty getProperty(final Element property) {
    final ODataProperty res;

    final Node nullNode = property.getAttributes().getNamedItem(ODataConstants.ATTR_NULL);

    if (nullNode == null) {
        final EdmType edmType = StringUtils.isBlank(property.getAttribute(ODataConstants.ATTR_M_TYPE)) ? null
                : new EdmType(property.getAttribute(ODataConstants.ATTR_M_TYPE));

        final PropertyType propType = edmType == null ? guessPropertyType(property)
                : edmType.isCollection() ? PropertyType.COLLECTION
                        : edmType.isSimpleType() ? PropertyType.PRIMITIVE : PropertyType.COMPLEX;

        switch (propType) {
        case COLLECTION:
            res = fromCollectionPropertyElement(property, edmType);
            break;

        case COMPLEX:
            res = fromComplexPropertyElement(property, edmType);
            break;

        case PRIMITIVE:
            res = fromPrimitivePropertyElement(property, edmType);
            break;

        case EMPTY:
        default:
            res = ODataFactory.newPrimitiveProperty(XMLUtils.getSimpleName(property), null);
        }
    } else {
        res = ODataFactory.newPrimitiveProperty(XMLUtils.getSimpleName(property), null);
    }

    return res;
}

From source file:edu.stanford.muse.slant.CustomSearchHelper.java

public static List<CSEDetails> getExistingCSEs(String authtoken) throws HttpException, IOException {
    HttpClient client = new HttpClient();

    GetMethod get = new GetMethod("http://www.google.com/cse/api/default/cse/");
    get.addRequestHeader("Content-type", "text/xml");
    get.addRequestHeader("Authorization", "GoogleLogin auth=" + authtoken);

    int astatusCode = client.executeMethod(get);

    List<CSEDetails> cses = new ArrayList<CSEDetails>();

    if (astatusCode == HttpStatus.SC_OK) {
        //If successful, the CSE annotation is displayed in the response.
        String s = get.getResponseBodyAsString();
        try {/*from  ww  w . j  ava 2s  .  c  o  m*/
            Document doc = loadXMLFromString(s);
            doc.getDocumentElement().normalize();

            NodeList nList = doc.getElementsByTagName("CustomSearchEngine");
            for (int temp = 0; temp < nList.getLength(); temp++) {

                Node nNode = nList.item(temp);
                if (nNode.getNodeType() == Node.ELEMENT_NODE) {

                    CSEDetails cse = new CSEDetails();

                    Element eElement = (Element) nNode;
                    String creator = eElement.getAttribute("creator"); // eElement is not HttpSession
                    if (creator != null)
                        cse.creator = creator;
                    eElement = (Element) nNode;
                    String title = eElement.getAttribute("title"); // eElement is not HttpSession
                    if (creator != null)
                        cse.title = title;
                    eElement = (Element) nNode;
                    String description = eElement.getAttribute("description"); // eElement is not HttpSession
                    if (creator != null)
                        cse.description = description;
                    cses.add(cse);
                }
            }
        } catch (Exception e) {
            Util.print_exception(e);
            return cses;
        }
        log.info("Existing CSEs: " + s);
    } else
        log.warn("get existing CSEs failed");
    return cses;
}

From source file:eu.semaine.util.XMLTool.java

/**
 * For the given element, return the value of the given attribute if it exists,
 * or null if it doesn't exist. Note that this is different from calling
 * e.getAttribute(), which will return the empty string both if the attribute
 * doesn't exist and if it exists and has the empty value. 
 * @param e//from www. j a  v  a  2  s  .  co  m
 * @param attributeName
 * @return the String value of the attribute if it exists, or null
 */
public static String getAttributeIfAvailable(Element e, String attributeName) {
    if (!e.hasAttribute(attributeName)) {
        return null;
    }
    return e.getAttribute(attributeName);
}

From source file:Main.java

public static Element getElement(Document document, String[] path, String value, String translate,
        String module) {//  w  w w.  jav  a 2s  .c o  m
    Node node = document;
    NodeList list;
    for (int i = 0; i < path.length; ++i) {
        list = node.getChildNodes();
        boolean found = false;
        for (int j = 0; j < list.getLength(); ++j) {
            Node testNode = list.item(j);
            if (testNode.getNodeName().equals(path[i])) {
                found = true;
                node = testNode;
                break;
            }
        }
        if (found == false) {
            Element element = document.createElement(path[i]);
            node.appendChild(element);
            node = element;
        }
    }
    if (value != null) {
        Text text = document.createTextNode(value);
        list = node.getChildNodes();
        boolean found = false;
        for (int j = 0; j < list.getLength(); ++j) {
            Node testNode = list.item(j);
            if (testNode instanceof Text) {
                node.replaceChild(text, testNode);
                found = true;
                break;
            }
        }
        if (!found)
            node.appendChild(text);
    }
    if (node instanceof Element) {
        Element element = (Element) node;
        if (translate != null && element.getAttribute("translate").equals("")) {
            element.setAttribute("translate", translate);
        }
        if (module != null && element.getAttribute("module").equals("")) {
            element.setAttribute("module", module);
        }
    }
    return (Element) node;
}

From source file:isl.FIMS.utils.Utils.java

public static void updateVocabularies(XMLEntity xmlE, String database, String xmlId, String xmlType,
        String dbPass, String dbUser, String lang) {
    String[] vocsToCheck = xmlE.queryString("//*[@sps_vocabulary!='' and @sps_id!='' and ./text()!='']");
    for (String vocTag : vocsToCheck) {
        Element e = Utils.getElement(vocTag);
        String sps_vocabulary = e.getAttribute("sps_vocabulary");
        String sps_id = e.getAttribute("sps_id");
        String text = e.getTextContent();
        DMSConfig vocConf = new DMSConfig(Utils.DBURI, Utils.systemDbCollection + "Vocabulary/", Utils.DBuser,
                Utils.DBpassword);/* w  w  w  .ja  v a2s  . c  o m*/
        Vocabulary voc = new Vocabulary(sps_vocabulary, lang, vocConf);
        String[] terms = voc.termValues();
        String addTerm = text;
        if (!Arrays.asList(terms).contains(addTerm)) {
            int id = voc.addTerm(addTerm);
            if (text.contains("'")) {
                xmlE.xUpdate(
                        "//*[@sps_vocabulary='" + sps_vocabulary + "'and ./text()=\"" + text + "\" ]/@sps_id",
                        String.valueOf(id));

            } else {
                xmlE.xUpdate(
                        "//*[@sps_vocabulary='" + sps_vocabulary + "'and ./text()='" + text + "' ]/@sps_id",
                        String.valueOf(id));

            }

        }
    }
}

From source file:org.brekka.stillingar.spring.config.ConfigurationServiceBeanDefinitionParser.java

/**
 * @param element//  w  w  w  .ja v a 2 s  . c om
 * @return
 */
protected static String getLoaderReference(Element element) {
    String id = element.getAttribute("id");
    return id + "-loader";
}

From source file:org.brekka.stillingar.spring.config.ConfigurationServiceBeanDefinitionParser.java

/**
 * @param element/*from  w  ww .  ja v a 2s  .co m*/
 * @return
 */
private static Engine determineEngine(Element element) {
    String engine = element.getAttribute("engine");
    engine = engine.toUpperCase();
    return Engine.valueOf(engine);
}

From source file:Main.java

/**
 * Get the text content of an element identified by a path,
 * where the path elements can include an index. The first
 * path element must not have an index, and its name must
 * match the name of the starting node. If the starting
 * node is a Document, the root Element of the document is
 * used as the starting point. Path elements must be separated
 * by the slash character. If the path starts with a slash,
 * the slash is ignored. If the element or attribute identified
 * by the path is not present as a child of the starting node,
 * the empty string is returned. If a path element identifies
 * an attribute, any subsequent path elements are ignored.
 * A path is in the form: /e1/e2/e3/... or /e1/e2/@attr
 * Note the slash preceding the attribute's @-sign.
 * @param node the starting node for the path. The first path
 * element must match the name of this node.
 * @param path the path to the target node.
 * @return the full text value of the target node (including all
 * descendent text nodes), or the empty string if the target is
 * not a descendent of the starting node.
 *//*from w  w  w.j  a v a2 s . co m*/
public static String getTextContent(Node node, String path) {
    if (node instanceof Document)
        node = ((Document) node).getDocumentElement();
    if (!(node instanceof Element))
        return "";
    Element el = (Element) node;
    path = path.replaceAll("\\s", "");
    if (path.startsWith("/"))
        path = path.substring(1);
    String[] pathElements = path.split("/");
    if (!pathElements[0].equals(el.getTagName()))
        return "";
    for (int i = 1; i < pathElements.length; i++) {
        String pe = pathElements[i];
        if (pe.startsWith("@")) {
            //If this path element identifies an attribute, return it
            //and ignore any further path elements.
            return el.getAttribute(pe.substring(1));
        } else {
            //This path element identifies an Element. It may have an index.
            //Get the index, if present, and get the element name.
            int n = 0;
            int k = pe.indexOf("[");
            int kk = pe.lastIndexOf("]");
            if ((k != -1) && (k < kk)) {
                try {
                    n = Integer.parseInt(pe.substring(k + 1, kk));
                } catch (Exception ex) {
                    return "";
                }
                pe = pe.substring(0, k);
            } else if (k != kk)
                return "";
            //We now have the element name and the index.
            //Find the identified Element. We have to count
            //matching elements to find the one identified
            //by the index.
            int nn = 0;
            Node child = el.getFirstChild();
            while (child != null) {
                if ((child.getNodeType() == Node.ELEMENT_NODE) && child.getNodeName().equals(pe)) {
                    if (n == nn)
                        break;
                    nn++;
                }
                child = child.getNextSibling();
            }
            //If the child is null, we didn't find the identified Element.
            if (child == null)
                return "";
            //If we get here, we found it, now look for the next one.
            el = (Element) child;
        }
    }
    //Okay, we must be at the end of the path, and it must be an Element.
    //Return the text content of the element.
    return el.getTextContent();
}

From source file:isl.FIMS.utils.Utils.java

public static ArrayList<String> checkReference(XMLEntity xmlE, String database, String xmlId, String xmlType,
        String dbUser, String dbPass) {
    ArrayList<String> missingFiles = new <String>ArrayList();
    String[] references = xmlE.queryString(
            "//*[name(.)!= 'ref' and name(.)!='ref_by'  and @sps_type!='' and @sps_id!='' and @sps_id!='0']");
    String[] oldRerences = xmlE.queryString("//admin/refs/ref");
    Set<String> afterEditingList = new HashSet();
    Set<String> beforeEditingList = new HashSet();
    for (int i = 0; i < oldRerences.length; i++) {
        Element e = Utils.getElement(oldRerences[i]);
        String sps_type = e.getAttribute("sps_type");
        String sps_id = e.getAttribute("sps_id");
        //h katw pavla xrhsimopoieitai gia na mporesume sth sunexeia na spasume to string
        beforeEditingList.add(sps_type + "_" + sps_id);
    }//from  w  w  w . j a v a 2s .c  o m
    for (int i = 0; i < references.length; i++) {
        Element e = Utils.getElement(references[i]);
        String sps_type = e.getAttribute("sps_type");
        String sps_id = e.getAttribute("sps_id");
        if (!afterEditingList.contains(sps_type + "_" + sps_id)) {
            String refCollection = "";
            try {
                refCollection = UtilsQueries.getpath(database,
                        ApplicationBasicServlet.systemDbCollection + sps_type, dbUser, dbPass, sps_type,
                        sps_id);
                DBFile refxml = new DBFile(database, refCollection, sps_type + sps_id + ".xml", dbUser, dbPass);
            } catch (Exception ex) {
                missingFiles.add(sps_type + "/" + sps_id);
            }
        }
        afterEditingList.add(sps_type + "_" + sps_id);

    }
    Collection notUsedReferences = Utils.Subtract(afterEditingList, beforeEditingList);
    Iterator<String> it = notUsedReferences.iterator();
    //removes references that are not used anymore
    while (it.hasNext()) {
        String removeRef = it.next();
        String removeType = removeRef.split("_")[0];
        String removeId = removeRef.split("_")[1];
        String removeCollection = "";
        try {
            removeCollection = UtilsQueries.getpath(database,
                    ApplicationBasicServlet.systemDbCollection + removeType, dbUser, dbPass, removeType,
                    removeId);
            DBFile removeXml = new DBFile(database, removeCollection, removeType + removeId + ".xml", dbUser,
                    dbPass);
        } catch (Exception e) {
            missingFiles.add(removeType + "/" + removeId);
        }
    }
    return missingFiles;
}

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 www  .  j ava2s .  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();
    }
}