Example usage for org.w3c.dom Node getTextContent

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

Introduction

In this page you can find the example usage for org.w3c.dom Node 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:com.swdouglass.joid.consumer.Discoverer.java

private XRDSDocument buildXrdsDocument(GetMethod get)
        throws ParserConfigurationException, SAXException, IOException {
    XRDSDocument doc = new XRDSDocument();
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    Document document = docBuilder.parse(get.getResponseBodyAsStream());
    get.releaseConnection();//www.java2 s  .com
    NodeList list = document.getElementsByTagName("Service");
    for (int i = 0; i < list.getLength(); i++) {
        Node node = list.item(i);
        //<Service priority="30" xmlns:openid="http://openid.net/xmlns/1.0">
        //  <Type>http://openid.net/signon/1.0</Type>
        //  <URI>http://www.livejournal.com/openid/server.bml</URI>
        //  <openid:Delegate>http://www.livejournal.com/users/frank/</openid:Delegate>
        //</Service>

        debug(nodeToString(node));// the Node.toString() isn't showing what we want
        NodeList childNodes = node.getChildNodes();
        XRDSService service = new XRDSService();
        Set<String> types = new LinkedHashSet<String>();
        for (int j = 0; j < childNodes.getLength(); j++) {
            //http://yadis.org/wiki/Yadis_1.0_(HTML)#7._The_Yadis_document    
            Node node2 = childNodes.item(j);
            if (!node2.getNodeName().equals("#text")) {
                debug(node2.getNodeName() + ": " + node2.getTextContent());
            }
            if (node2.getNodeName().equalsIgnoreCase("URI")) {
                service.setUri(node2.getTextContent());
            } else if (node2.getNodeName().equalsIgnoreCase("openid:Delegate")) {
                service.setOpenIDDelegate(node2.getTextContent());
            } else if (node2.getNodeName().equalsIgnoreCase("type")) {
                types.add(node2.getTextContent());
                if (!"http://openid.net/signon/1.0".equalsIgnoreCase(node2.getTextContent())) {
                    log.warn("XRDS service type is NOT http://openid.net/signon/1.0");
                    // TODO: throw an exception? do I care?
                    //http://openid.net/srv/ax/1.0
                    //http://specs.openid.net/auth/2.0/server
                }
                service.setType(types);
            }
        }
        doc.addService(service);
    }
    debug(doc.toString());
    return doc;
}

From source file:de.tudarmstadt.ukp.dkpro.core.io.xml.XmlReaderXPath.java

private void ensureIdValidity(Node node) {
    NodeList idNodes = null;/* w  w  w  .j  a va  2 s  . c  o  m*/
    try {
        idNodes = (NodeList) compiledIdXPath.evaluate(node, XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
        // Already checked in initialize(), should not happen.
        getUimaContext().getLogger().log(Level.WARNING, e.getLocalizedMessage());
        return;
    }

    if (idNodes.getLength() == 0) {
        // DocID not found
        throw new IllegalStateException(
                "DocID tag \"" + docIdTag + "\" not found: " + currentFileResource.getFile().getAbsolutePath());
    } else if (idNodes.getLength() != 1) {
        // DocID not unique (two id elements in one doc)
        throw new IllegalStateException("DocID tag \"" + docIdTag + "\" has multiple occurences: "
                + currentFileResource.getFile().getAbsolutePath());
    }

    Node idNode = idNodes.item(0);
    String id = idNode.getTextContent();
    if (StringUtils.isEmpty(id)) {
        // Empty DocID (e.g. <num></num>)
        throw new IllegalStateException("Emtpy DocID tag \"" + docIdTag + "\" in file: "
                + currentFileResource.getFile().getAbsolutePath());
    }

    getUimaContext().getLogger().log(Level.INFO, "ID '" + id + "' found");
}

From source file:com.cloud.test.stress.StressTestDirectAttach.java

public static Map<String, List<String>> getMultipleValuesFromXML(InputStream is, String[] tagNames) {
    Map<String, List<String>> returnValues = new HashMap<String, List<String>>();
    try {//from  w  ww .j  a  v a 2  s.  co m
        DocumentBuilder docBuilder = factory.newDocumentBuilder();
        Document doc = docBuilder.parse(is);
        Element rootElement = doc.getDocumentElement();
        for (int i = 0; i < tagNames.length; i++) {
            NodeList targetNodes = rootElement.getElementsByTagName(tagNames[i]);
            if (targetNodes.getLength() <= 0) {
                s_logger.error("no " + tagNames[i] + " tag in XML response...returning null");
            } else {
                List<String> valueList = new ArrayList<String>();
                for (int j = 0; j < targetNodes.getLength(); j++) {
                    Node node = targetNodes.item(j);
                    valueList.add(node.getTextContent());
                }
                returnValues.put(tagNames[i], valueList);
            }
        }
    } catch (Exception ex) {
        s_logger.error(ex);
    }
    return returnValues;
}

From source file:be.fedict.eid.applet.service.signer.ooxml.RelationshipTransformService.java

@Override
public void init(XMLStructure parent, XMLCryptoContext context) throws InvalidAlgorithmParameterException {
    LOG.debug("init(parent,context)");
    LOG.debug("parent java type: " + parent.getClass().getName());
    DOMStructure domParent = (DOMStructure) parent;
    Node parentNode = domParent.getNode();
    try {//from  w  w  w  .j a va  2 s.  c o m
        LOG.debug("parent: " + toString(parentNode));
    } catch (TransformerException e) {
        throw new InvalidAlgorithmParameterException();
    }

    Element nsElement = parentNode.getOwnerDocument().createElement("ns");
    nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:ds", Constants.SignatureSpecNS);
    nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:mdssi",
            "http://schemas.openxmlformats.org/package/2006/digital-signature");

    /*
     * RelationshipReference
     */
    NodeList nodeList;
    try {
        nodeList = XPathAPI.selectNodeList(parentNode, "mdssi:RelationshipReference/@SourceId", nsElement);
    } catch (TransformerException e) {
        LOG.error("transformer exception: " + e.getMessage(), e);
        throw new InvalidAlgorithmParameterException();
    }
    for (int nodeIdx = 0; nodeIdx < nodeList.getLength(); nodeIdx++) {
        Node node = nodeList.item(nodeIdx);
        String sourceId = node.getTextContent();
        LOG.debug("sourceId: " + sourceId);
        this.sourceIds.add(sourceId);
    }

    /*
     * RelationshipsGroupReference
     */
    try {
        nodeList = XPathAPI.selectNodeList(parentNode, "mdssi:RelationshipsGroupReference/@SourceType",
                nsElement);
    } catch (TransformerException e) {
        LOG.error("transformer exception: " + e.getMessage(), e);
        throw new InvalidAlgorithmParameterException();
    }
    for (int nodeIdx = 0; nodeIdx < nodeList.getLength(); nodeIdx++) {
        Node node = nodeList.item(nodeIdx);
        String sourceType = node.getTextContent();
        LOG.debug("sourceType: " + sourceType);
        this.sourceTypes.add(sourceType);
    }
}

From source file:com.github.xdcrafts.flower.spring.impl.xml.ExtensionBeanDefinitionHandler.java

protected void doParse(Element element, BeanDefinitionBuilder bean) {
    final Map<Object, Object> configuration = new ManagedMap<>();
    final Node keywordValueNode = element
            .getElementsByTagNameNS("http://xdcrafts.github.com/schema/flower", "keyword-value").item(0);
    final Node predicateNode = element
            .getElementsByTagNameNS("http://xdcrafts.github.com/schema/flower", "predicate").item(0);
    if (keywordValueNode != null) {
        configuration.put("keyword-value", keywordValueNode.getTextContent());
    }/*from   ww w  .j av  a  2 s.  com*/
    if (predicateNode != null) {
        configuration.put("predicate", new RuntimeBeanReference(predicateNode.getTextContent()));
    }
    bean.addPropertyReference("action", element.getAttribute("action")).addPropertyValue("configuration",
            configuration);
}

From source file:fr.free.movierenamer.scrapper.impl.trailer.VideoDetectiveScrapper.java

@Override
protected List<Trailer> searchTrailer(Media media) throws Exception {

    List<Trailer> trailers = new ArrayList<Trailer>();
    String search = media.getOriginalName();
    if (search == null || search.equals("")) {
        search = media.getName();//from  w  w w . j a v  a2 s  . c o m
    }

    URL searchUrl = new URL("http", host,
            "/browse?filter=mediatype%3aMovie+Alternate+Version&q=" + URIRequest.encode(search));
    Document dom = URIRequest.getHtmlDocument(searchUrl.toURI());
    List<Node> nodes = XPathUtils.selectNodes("//DIV[contains(@class, 'durationwrapper')]", dom);

    for (Node node : nodes) {
        Node info = XPathUtils.selectNode("DIV[@class='duration']//A[contains(@href, '/movies/')]", node);
        if (info != null) {

            String title = info.getTextContent();
            if (!isTrailerof(title, media)) {
                continue;
            }

            String runtime = XPathUtils.selectString("DIV[@class='durationtext']", node).trim();

            URL thumbUrl = null;
            String thumb = XPathUtils.selectString("A[contains(@href, '/movies/')]/IMG/@src", node);
            if (thumb != null && !thumb.equals("")) {
                try {
                    thumbUrl = new URL(thumb);
                } catch (MalformedURLException ex) {
                }
            }

            URL trailerUrl = null;
            String turlStr = XPathUtils.getAttribute("href", info);
            try {
                trailerUrl = new URL("http", host, turlStr);
            } catch (MalformedURLException ex) {
            }

            Node lnode = XPathUtils
                    .selectNode("DIV[@class='duration']//DIV[last()]/text()[preceding-sibling::BR]", node);
            AvailableLanguages lang = null;
            if (lnode != null) {
                Locale local = LocaleUtils.findLanguage(lnode.getTextContent().trim());
                if (local != null) {
                    try {
                        lang = AvailableLanguages.valueOf(local.getLanguage());
                    } catch (Exception ex) {
                    }
                }
            }

            trailers.add(new Trailer(title, runtime, name, thumbUrl, trailerUrl, lang));
        }
    }

    return trailers;
}

From source file:com.epam.catgenome.manager.externaldb.ncbi.parser.NCBIGeneInfoParser.java

private void fillGeneAlsoKnownList(NodeList alsoKnown, List<String> alsoKnownList)
        throws XPathExpressionException {
    for (int i = 0; i < alsoKnown.getLength(); i++) {
        Node item = alsoKnown.item(i).cloneNode(true);
        alsoKnownList.add(item.getTextContent());
    }/*from  w ww  .j a v  a2 s. c  om*/
}

From source file:com.oracle.tutorial.jdbc.ProductInformationTable.java

public void populateTable(String fileName)
        throws SQLException, ParserConfigurationException, SAXException, IOException, XPathExpressionException {
    javax.xml.parsers.DocumentBuilderFactory factory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
    // factory.setNamespaceAware(true);
    factory.setNamespaceAware(true);/*w  ww  . j  av a  2 s  .  c  om*/
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(fileName);

    XPathFactory xPathfactory = XPathFactory.newInstance();

    XPath xPath = xPathfactory.newXPath();

    NodeList nodes = (NodeList) xPath.evaluate("/coffee-product-information/item[coffee = 'Columbian']", doc,
            XPathConstants.NODESET);

    for (int i = 0; i < nodes.getLength(); i++) {
        Node currentNode = nodes.item(i);
        // Retrieve the description element

        currentNode.normalize();

        if (currentNode == null) {
            System.out.println("Current node is null");
        }

        //      System.out.println(currentNode.getTextContent());

        Node descriptionNode = (Node) xPath.evaluate("description", currentNode, XPathConstants.NODE);

        if (descriptionNode == null) {
            System.out.println("DescriptionNode is null");
        } else {

            System.out.println(descriptionNode.getTextContent());

            NodeList descriptionNodeChildren = descriptionNode.getChildNodes();
            System.out.println("Description node has " + descriptionNodeChildren.getLength() + " child nodes");
            Node descNodeChild = descriptionNode.getFirstChild();
            System.out.println("Only child node type: " + descNodeChild.getNodeType());
        }

        //      System.out.println("Description: " + descriptionNode.getNodeValue());

        // System.out.println(nodes.item(i).getNodeValue());
    }

}

From source file:com.qcadoo.plugin.internal.descriptorparser.DefaultPluginDescriptorParser.java

private String getTextContent(final Node node) {
    String result = node.getTextContent();
    if (result != null) {
        result = result.trim();//from  www  . j av  a 2 s . com
        if (result.isEmpty()) {
            return null;
        }
        return result;
    }
    return null;
}

From source file:cz.muni.fi.mir.similarity.SimilarityFormConverter.java

/**
 * Method used for traveling inside XML tree. We recursively call this
 * method on each node. Last node, that has some text has 1 child <b>text
 * node</b>, thats why we stop there, and append its contents into
 * StringBuilder class.//from  w ww.  ja  v  a 2  s.  c o  m
 *
 * @param node to be examined
 * @param sb into which is output text appended
 */
private void distanceTravel(Node node, StringBuilder sb) {
    if (node == null) {
        return;
    }

    NodeList nodeList = node.getChildNodes();
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node currentNode = nodeList.item(i);
        if (currentNode.getNodeType() == Node.ELEMENT_NODE) { //last node has 1 child ~> text value
            if (currentNode.getChildNodes().getLength() == 1) {
                sb.append(StringUtils.trimAllWhitespace(currentNode.getTextContent()));
            } else { // there is something more so we continue in greater depth
                distanceTravel(currentNode, sb);
            }
        }
    }
}