Example usage for org.w3c.dom Element getTextContent

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

Introduction

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

Prototype

public String getTextContent() throws DOMException;

Source Link

Document

This attribute returns the text content of this node and its descendants.

Usage

From source file:net.roboconf.target.azure.internal.AzureIaasHandler.java

private static boolean getExistResutlFromXML(String xmlStr, String nameOfNode)
        throws ParserConfigurationException, SAXException, IOException {

    DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
    DocumentBuilder b;/*from  w w w .  j  av  a  2  s  .  c om*/
    b = f.newDocumentBuilder();
    Document doc;
    doc = b.parse(new ByteArrayInputStream(xmlStr.getBytes("UTF-8")));
    NodeList nodes = doc.getElementsByTagName(nameOfNode);
    String result = "false";
    for (int i = 0; i < nodes.getLength(); i++) {
        Element node = (Element) nodes.item(i);
        result = node.getTextContent();
    }

    return Boolean.parseBoolean(result);
}

From source file:com.googlecode.sardine.util.SardineUtil.java

/** */
public static Map<String, String> extractCustomProps(List<Element> elements) {
    Map<String, String> customPropsMap = new HashMap<String, String>(elements.size());

    for (Element element : elements) {
        String[] keys = element.getTagName().split(":", 2);
        String key = (keys.length > 1) ? keys[1] : keys[0];

        customPropsMap.put(key, element.getTextContent());
    }//from www  . j a va 2s  . c  o  m

    return customPropsMap;
}

From source file:org.zaizi.oauth2utils.OAuthUtils.java

public static void parseXMLDoc(Element element, Document doc, Map<String, String> oauthResponse) {
    NodeList child = null;/*  w  w  w.j  av  a 2  s .  c  o  m*/
    if (element == null) {
        child = doc.getChildNodes();

    } else {
        child = element.getChildNodes();
    }
    for (int j = 0; j < child.getLength(); j++) {
        if (child.item(j).getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
            org.w3c.dom.Element childElement = (org.w3c.dom.Element) child.item(j);
            if (childElement.hasChildNodes()) {
                System.out.println(childElement.getTagName() + " : " + childElement.getTextContent());
                oauthResponse.put(childElement.getTagName(), childElement.getTextContent());
                parseXMLDoc(childElement, null, oauthResponse);
            }

        }
    }
}

From source file:com.codebutler.farebot.card.felica.FelicaCard.java

public static FelicaCard fromXml(byte[] tagId, Date scannedAt, Element element) {
    Element systemsElement = (Element) element.getElementsByTagName("systems").item(0);

    NodeList systemElements = systemsElement.getElementsByTagName("system");

    FeliCaLib.IDm idm = new FeliCaLib.IDm(
            Base64.decode(element.getElementsByTagName("idm").item(0).getTextContent(), Base64.DEFAULT));
    FeliCaLib.PMm pmm = new FeliCaLib.PMm(
            Base64.decode(element.getElementsByTagName("pmm").item(0).getTextContent(), Base64.DEFAULT));

    FelicaSystem[] systems = new FelicaSystem[systemElements.getLength()];

    for (int x = 0; x < systemElements.getLength(); x++) {
        Element systemElement = (Element) systemElements.item(x);

        int systemCode = Integer.parseInt(systemElement.getAttribute("code"));

        Element servicesElement = (Element) systemElement.getElementsByTagName("services").item(0);

        NodeList serviceElements = servicesElement.getElementsByTagName("service");

        FelicaService[] services = new FelicaService[serviceElements.getLength()];

        for (int y = 0; y < serviceElements.getLength(); y++) {
            Element serviceElement = (Element) serviceElements.item(y);
            int serviceCode = Integer.parseInt(serviceElement.getAttribute("code"));

            Element blocksElement = (Element) serviceElement.getElementsByTagName("blocks").item(0);

            NodeList blockElements = blocksElement.getElementsByTagName("block");

            FelicaBlock[] blocks = new FelicaBlock[blockElements.getLength()];

            for (int z = 0; z < blockElements.getLength(); z++) {
                Element blockElement = (Element) blockElements.item(z);
                byte address = Byte.parseByte(blockElement.getAttribute("address"));
                byte[] data = Base64.decode(blockElement.getTextContent(), Base64.DEFAULT);

                blocks[z] = new FelicaBlock(address, data);
            }//from  w  w  w  .  j a va 2s  . c om

            services[y] = new FelicaService(serviceCode, blocks);
        }

        systems[x] = new FelicaSystem(systemCode, services);
    }

    return new FelicaCard(tagId, scannedAt, idm, pmm, systems);
}

From source file:com.omertron.yamjtrakttv.tools.CompleteMoviesTools.java

/**
 * Parse the video element and extract the information from it.
 *
 * @param eVideo//from  w ww . j  a va  2s. co m
 * @return
 */
public static Video parseVideo(Element eVideo) {
    Video v = new Video();
    v.setTitle(DOMHelper.getValueFromElement(eVideo, "title"));
    v.setYear(DOMHelper.getValueFromElement(eVideo, "year"));
    v.setType(DOMHelper.getValueFromElement(eVideo, "movieType"));
    v.setWatched(Boolean.parseBoolean(DOMHelper.getValueFromElement(eVideo, "watched")));

    String stringDate = DOMHelper.getValueFromElement(eVideo, "watchedDate");
    if (StringUtils.isNumeric(stringDate) && !"0".equals(stringDate)) {
        v.setWatchedDate(new Date(Long.parseLong(stringDate)));
    } else {
        LOG.debug("Invalid watched date '" + stringDate + "' using current date");
        v.setWatchedDate(new Date());
        // Because the date was set by us, let's add a small (1 second) delay to ensure that we don't get identical watched dates
        try {
            TimeUnit.SECONDS.sleep(DEFAULT_DELAY);
        } catch (InterruptedException ex) {
            // Don't care if we are interrupted or not.
        }
    }

    NodeList nlID = eVideo.getElementsByTagName("id");
    if (nlID.getLength() > 0) {
        Node nID;
        Element eID;
        for (int loop = 0; loop < nlID.getLength(); loop++) {
            nID = nlID.item(loop);
            if (nID.getNodeType() == Node.ELEMENT_NODE) {
                eID = (Element) nID;
                String moviedb = eID.getAttribute("movieDatabase");
                if (StringUtils.isNotBlank(moviedb)) {
                    v.addId(moviedb, eID.getTextContent());
                }
            }
        }
    }

    // TV specific processing
    if (v.isTvshow()) {
        v.addEpisodes(parseTvFiles(eVideo));
    }

    return v;
}

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

/**
 *
 * @param filePath : file path/*  www .j a  v a 2  s . com*/
 * @param tagName : tag name
 * @return : value of the elements
 */
public static String[] getDataFromXmlByTagName(String filePath, String tagName) {
    String[] data = null;
    try {
        File file = new File(filePath);

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

        //optional, but recommended
        //read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
        doc.getDocumentElement().normalize();

        //System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

        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) {

                Element eElement = (Element) nNode;
                dataList.add(eElement.getTextContent());
                //System.out.println("file type : " + eElement.getTextContent() + "\n");

            }
        }

        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, ex);
    }
    return data;
}

From source file:org.apache.lens.regression.util.Util.java

public static void changeConfig(HashMap<String, String> map, String remotePath) throws Exception {

    Path p = Paths.get(remotePath);
    String fileName = p.getFileName().toString();
    backupFile = localFilePath + "backup-" + fileName;
    localFile = localFilePath + fileName;
    log.info("Copying " + remotePath + " to " + localFile);
    remoteFile("get", remotePath, localFile);
    Files.copy(new File(localFile).toPath(), new File(backupFile).toPath(), REPLACE_EXISTING);

    DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document doc = docBuilder.parse(new FileInputStream(localFile));
    doc.normalize();//from  w  ww  .  j a  va2 s.  co  m

    NodeList rootNodes = doc.getElementsByTagName("configuration");
    Node root = rootNodes.item(0);
    Element rootElement = (Element) root;
    NodeList property = rootElement.getElementsByTagName("property");

    for (int i = 0; i < property.getLength(); i++) { //Deleting redundant properties from the document
        Node prop = property.item(i);
        Element propElement = (Element) prop;
        Node propChild = propElement.getElementsByTagName("name").item(0);

        Element nameElement = (Element) propChild;
        if (map.containsKey(nameElement.getTextContent())) {
            rootElement.removeChild(prop);
            i--;
        }
    }

    Iterator<Entry<String, String>> ab = map.entrySet().iterator();
    while (ab.hasNext()) {
        Entry<String, String> entry = ab.next();
        String propertyName = entry.getKey();
        String propertyValue = entry.getValue();
        System.out.println(propertyName + " " + propertyValue + "\n");
        Node newNode = doc.createElement("property");
        rootElement.appendChild(newNode);
        Node newName = doc.createElement("name");
        Element newNodeElement = (Element) newNode;

        newName.setTextContent(propertyName);
        newNodeElement.appendChild(newName);

        Node newValue = doc.createElement("value");
        newValue.setTextContent(propertyValue);
        newNodeElement.appendChild(newValue);
    }
    prettyPrint(doc);
    remoteFile("put", remotePath, localFile);
}

From source file:org.openiot.gsn.utils.GSNMonitor.java

public static void parseXML(String s) {
    try {//from  w w  w  .  jav a  2s  . co  m

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        InputSource inputSource = new InputSource();
        inputSource.setCharacterStream(new StringReader(s));

        Document document = documentBuilder.parse(inputSource);
        NodeList nodes = document.getElementsByTagName("virtual-sensor");

        for (int i = 0; i < nodes.getLength(); i++) {
            Element element = (Element) nodes.item(i);

            String sensor_name = element.getAttribute("name");

            if (!sensorsUpdateDelay.containsKey(sensor_name))
                continue; // skip sensors that are not monitored

            logger.warn("Sensor: " + sensor_name);

            NodeList listOfField = element.getElementsByTagName("field");
            for (int j = 0; j < listOfField.getLength(); j++) {
                Element line = (Element) listOfField.item(j);

                if (line.getAttribute("name").indexOf("timed") >= 0) {
                    String last_updated_as_string = line.getTextContent();

                    try {
                        Long last_updated_as_Long = GregorianCalendar.getInstance().getTimeInMillis()
                                - VSensorMonitorConfig.datetime2timestamp(last_updated_as_string);
                        logger.warn(new StringBuilder(last_updated_as_string).append(" => ")
                                .append(VSensorMonitorConfig.ms2dhms(last_updated_as_Long)).toString());

                        sensorsUpdateDelay.put(sensor_name, last_updated_as_Long);
                    } catch (ParseException e) {
                        errorsBuffer.append("Last update time for sensor ").append(sensor_name)
                                .append(" cannot be read. Error while parsing > ")
                                .append(last_updated_as_string).append(" <\n");
                    }
                }
            }
        }
    } catch (Exception e) {
        logger.warn("Exception while parsing XML\n");
        e.printStackTrace();
    }
}

From source file:org.apache.ofbiz.passport.user.LinkedInAuthenticator.java

public static String getLinkedInUserId(Document userInfo) {
    NodeList persons = userInfo.getElementsByTagName("person");
    if (UtilValidate.isEmpty(persons) || persons.getLength() <= 0) {
        return null;
    }/*from   w ww  .jav a  2s .  c o  m*/
    Element standardProfileRequest = UtilXml.firstChildElement((Element) persons.item(0),
            "site-standard-profile-request");
    Element url = UtilXml.firstChildElement(standardProfileRequest, "url");
    if (UtilValidate.isNotEmpty(url)) {
        String urlContent = url.getTextContent();
        if (UtilValidate.isNotEmpty(urlContent)) {
            String id = urlContent.substring(urlContent.indexOf("?id="));
            id = id.substring(0, id.indexOf("&"));
            Debug.logInfo("LinkedIn user id: " + id, module);
            return id;
        }
    }
    return null;
}

From source file:org.apache.ofbiz.passport.user.LinkedInAuthenticator.java

public static Map<String, String> parseLinkedInUserInfo(Document userInfo) {
    Map<String, String> results = new HashMap<String, String>();
    NodeList persons = userInfo.getElementsByTagName("person");
    if (UtilValidate.isEmpty(persons) || persons.getLength() <= 0) {
        return results;
    }/*from ww  w  . ja  va 2 s  . c  o  m*/
    Element person = (Element) persons.item(0);
    Element standardProfileRequest = UtilXml.firstChildElement(person, "site-standard-profile-request");
    Element url = UtilXml.firstChildElement(standardProfileRequest, "url");
    if (UtilValidate.isNotEmpty(url)) {
        String urlContent = url.getTextContent();
        if (UtilValidate.isNotEmpty(urlContent)) {
            String id = urlContent.substring(urlContent.indexOf("?id="));
            id = id.substring(0, id.indexOf("&"));
            Debug.logInfo("LinkedIn user id: " + id, module);
            results.put("userId", id);
        }
    }
    Element firstNameElement = UtilXml.firstChildElement(person, "first-name");
    if (UtilValidate.isNotEmpty(firstNameElement)
            && UtilValidate.isNotEmpty(firstNameElement.getTextContent())) {
        results.put("firstName", firstNameElement.getTextContent());
    }
    Element lastNameElement = UtilXml.firstChildElement(person, "last-name");
    if (UtilValidate.isNotEmpty(lastNameElement) && UtilValidate.isNotEmpty(lastNameElement.getTextContent())) {
        results.put("lastName", lastNameElement.getTextContent());
    }
    Element emailElement = UtilXml.firstChildElement(person, "email-address");
    if (UtilValidate.isNotEmpty(emailElement) && UtilValidate.isNotEmpty(emailElement.getTextContent())) {
        results.put("emailAddress", emailElement.getTextContent());
    }
    return results;
}