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.flexive.war.beans.admin.RssProviderBean.java

/**
 * Fetch and parse a news feed (currently only tested with blog.flexive.org).
 *
 * @param url      the feed URL//from  www. j  a  va  2s.c  o  m
 * @param maxItems the maximum number of items returned
 * @return the news items
 */
private List<RssEntry> fetchFeed(String url, int maxItems) {
    HttpURLConnection urlConnection = null;
    InputStream in = null;
    try {
        // open url
        urlConnection = (HttpURLConnection) new URL(url).openConnection();
        urlConnection.setConnectTimeout(2000);
        in = urlConnection.getInputStream();

        // parse RSS feed
        final DocumentBuilder domBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        final Document doc = domBuilder.parse(new InputSource(in));

        // iterate over items
        final NodeList items = doc.getElementsByTagName("item");
        final int numItems = Math.min(items.getLength(), maxItems);
        final List<RssEntry> result = new ArrayList<RssEntry>(numItems);
        for (int i = 0; i < numItems; i++) {
            final NodeList childNodes = items.item(i).getChildNodes();
            String title = null;
            String link = null;
            // find title and link children
            for (int j = 0; j < childNodes.getLength(); j++) {
                final Node child = childNodes.item(j);
                if ("title".equals(child.getNodeName())) {
                    title = child.getTextContent();
                    if (link != null) {
                        break;
                    }
                } else if ("link".equals(child.getNodeName())) {
                    link = child.getTextContent();
                    if (title != null) {
                        break;
                    }
                }
            }
            if (title != null && link != null) {
                result.add(new RssEntry(title, link));
            }
        }
        return result;

    } catch (IOException e) {
        LOG.error("Failed to fetch stream from " + url + ": " + e.getMessage(), e);
        return new ArrayList<RssEntry>(0);
    } catch (SAXException e) {
        LOG.error("Failed to parse XML stream: " + url + ": " + e.getMessage(), e);
        return new ArrayList<RssEntry>(0);
    } catch (ParserConfigurationException e) {
        LOG.error("Failed to create parser: " + url + ": " + e.getMessage(), e);
        return new ArrayList<RssEntry>(0);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                LOG.warn("Failed to close input stream: " + e.getMessage(), e);
            }
        }
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
}

From source file:com.mingo.parser.xml.dom.QuerySetParser.java

/**
 * Parse <queryFragment/> tag.// ww  w  . j  a  v  a  2  s. c  o  m
 *
 * @param fragmentNode node
 * @return {@link QueryCase}
 */
private QueryFragment parseQueryFragment(Node fragmentNode) {
    String fragmentId = getAttributeString(fragmentNode, ID);
    String fragmentBody = processString(fragmentNode.getTextContent());
    return new QueryFragment(fragmentId, fragmentBody);
}

From source file:eu.europa.ec.markt.dss.validation102853.xml.XmlNode.java

/**
 * @param xmlNode the {@code XmlNode} to which the element is added
 * @param element the {@code Node} to be copied
 *///from  w w w .  j av  a2  s  .  c om
private static void recursiveCopy(final XmlNode xmlNode, final Node element) {

    final String name = element.getNodeName();
    final XmlNode _xmlNode = new XmlNode(name);
    final NamedNodeMap attributes = element.getAttributes();
    for (int jj = 0; jj < attributes.getLength(); jj++) {

        final Node attrNode = attributes.item(jj);
        final String attrName = attrNode.getNodeName();
        if (!"xmlns".equals(attrName)) {

            _xmlNode.setAttribute(attrName, attrNode.getNodeValue());
        }
    }

    final NodeList nodes = element.getChildNodes();
    boolean hasElementNodes = false;
    for (int ii = 0; ii < nodes.getLength(); ii++) {

        final Node node = nodes.item(ii);
        if (node.getNodeType() == Node.ELEMENT_NODE) {

            hasElementNodes = true;
            recursiveCopy(_xmlNode, node);
        }
    }
    if (!hasElementNodes) {

        final String value = element.getTextContent();
        _xmlNode.setValue(value);
    }
    _xmlNode.setParent(xmlNode);
}

From source file:Importers.ImportReportCompiler.java

private Host getHost(Node n) {
    Host host = new Host();
    NodeList children = n.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
        Node node = children.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            String name = node.getNodeName();
            String value = node.getTextContent();

            if (name.equalsIgnoreCase("ip-address")) {
                host.setIp_address(value);
            } else if (name.equalsIgnoreCase("hostname")) {
                host.setHostname(value);
            } else if (name.equalsIgnoreCase("netbios-name")) {
                host.setNetbios_name(value);
            } else if (name.equalsIgnoreCase("operating-system")) {
                host.setOperating_system(value);
            } else if (name.equalsIgnoreCase("mac-address")) {
                host.setMac_address(value);
            } else if (name.equalsIgnoreCase("portnumber")) {
                host.setPortnumber(value);
            } else if (name.equalsIgnoreCase("protocol")) {
                host.setProtocol(value);
            } else if (name.equalsIgnoreCase("note")) {
                Note note = new Note(new String(new Base64().decode(value)));
                host.setNotes(note);//from  w w  w.  j  ava 2s  .c om
            }
        }
    }
    return host;
}

From source file:eu.impact_project.wsclient.XmlServiceProvider.java

private Service createServiceObjectFor(Node service) {

    int id = Integer.valueOf(service.getAttributes().getNamedItem("id").getTextContent());

    String urlString = "";
    String title = "";
    String description = "";

    NodeList nodes = service.getChildNodes();
    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        String nodeName = node.getLocalName();
        if (nodeName != null && nodeName.equals("url"))
            urlString = node.getTextContent();
        else if (nodeName != null && nodeName.equals("title"))
            title = node.getTextContent();
        else if (nodeName != null && nodeName.equals("description"))
            description = node.getTextContent().trim();
    }//from   w  w  w .  j  a  v a  2s  . c o  m

    URL wsdlUrl = null;
    try {
        wsdlUrl = new URL(urlString);
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (DOMException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    Service result = new XmlService(id, title, description, wsdlUrl);

    return result;
}

From source file:org.jboss.windup.decorator.xml.XPathSummaryDecorator.java

protected String convertNode(Node node) throws TransformerException {
    StringWriter sw = new StringWriter();
    Transformer t = TransformerFactory.newInstance().newTransformer();
    t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    sw.append(node.getTextContent());/*from w  ww.j a  v a2s .c  o m*/
    return sw.toString();
}

From source file:eu.guardiansystems.livesapp.android.ui.GMapDirections.java

public ArrayList<LatLng> getDirection(Document doc) {
    if (doc == null)
        return new ArrayList<LatLng>();
    NodeList nl1, nl2, nl3;//  w  w  w .jav a  2  s  .com
    ArrayList<LatLng> listGeopoints = new ArrayList<LatLng>();
    nl1 = doc.getElementsByTagName("step");
    if (nl1.getLength() > 0) {
        for (int i = 0; i < nl1.getLength(); i++) {
            Node node1 = nl1.item(i);
            nl2 = node1.getChildNodes();

            Node locationNode = nl2.item(getNodeIndex(nl2, "start_location"));
            nl3 = locationNode.getChildNodes();
            Node latNode = nl3.item(getNodeIndex(nl3, "lat"));
            double lat = Double.parseDouble(latNode.getTextContent());
            Node lngNode = nl3.item(getNodeIndex(nl3, "lng"));
            double lng = Double.parseDouble(lngNode.getTextContent());
            listGeopoints.add(new LatLng(lat, lng));

            locationNode = nl2.item(getNodeIndex(nl2, "polyline"));
            nl3 = locationNode.getChildNodes();
            latNode = nl3.item(getNodeIndex(nl3, "points"));
            ArrayList<LatLng> arr = decodePoly(latNode.getTextContent());
            for (int j = 0; j < arr.size(); j++) {
                listGeopoints.add(new LatLng(arr.get(j).latitude, arr.get(j).longitude));
            }

            locationNode = nl2.item(getNodeIndex(nl2, "end_location"));
            nl3 = locationNode.getChildNodes();
            latNode = nl3.item(getNodeIndex(nl3, "lat"));
            lat = Double.parseDouble(latNode.getTextContent());
            lngNode = nl3.item(getNodeIndex(nl3, "lng"));
            lng = Double.parseDouble(lngNode.getTextContent());
            listGeopoints.add(new LatLng(lat, lng));
        }
    }

    return listGeopoints;
}

From source file:com.msopentech.odatajclient.engine.data.AbstractODataReader.java

@Override
public ODataProperty readProperty(final InputStream input, final ODataFormat format) {
    final Element property = client.getDeserializer().toPropertyDOM(input, format);

    // The ODataProperty object is used either for actual entity properties and for invoke result (when return type
    // is neither an entity nor a collection of entities).
    // Such formats are mostly the same except for collections: an entity property looks like
    //     <aproperty m:type="Collection(AType)">
    //       <element>....</element>
    //     </aproperty>
    ////from  ww w. j  a  v  a2s . com
    // while an invoke result with returnType="Collection(AnotherType)" looks like
    //     <functionImportName>
    //       <element m:type="AnotherType">...</element>
    //     <functionImportName>
    //
    // The code below is meant for "normalizing" the latter into
    //     <functionImportName m:type="Collection(AnotherType)">
    //       <element m:type="AnotherType">...</element>
    //     <functionImportName>
    final String type = property.getAttribute(ODataConstants.ATTR_M_TYPE);
    final NodeList elements = property.getElementsByTagName(ODataConstants.ELEM_ELEMENT);
    if (StringUtils.isBlank(type) && elements != null && elements.getLength() > 0) {
        final Node elementType = elements.item(0).getAttributes().getNamedItem(ODataConstants.ATTR_M_TYPE);
        if (elementType != null) {
            property.setAttribute(ODataConstants.ATTR_M_TYPE,
                    "Collection(" + elementType.getTextContent() + ")");
        }
    }

    return client.getBinder().getProperty(property);
}

From source file:edu.illinois.cs.cogcomp.temporal.normalizer.main.TemporalNormalizerBenchmark.java

/**
 * Setting up TemporalChunkerAnnotator, prepare dataset
 * @param fullFolderName folder name of the dataset
 * @param useHeidelTime boolean whether use HeidelTime for normalization or not
 * @throws IOException/*www .j  av a2s .  com*/
 * @throws ParserConfigurationException
 * @throws SAXException
 */
public void setUp(String fullFolderName, boolean useHeidelTime)
        throws IOException, ParserConfigurationException, SAXException {
    testText = new ArrayList<>();
    DCTs = new ArrayList<>();
    docIDs = new ArrayList<>();
    te3inputText = new ArrayList<>();

    Properties rmProps = new TemporalChunkerConfigurator().getDefaultConfig().getProperties();
    rmProps.setProperty("useHeidelTime", useHeidelTime ? "True" : "False");
    tca = new TemporalChunkerAnnotator(new ResourceManager(rmProps));

    File folder = new File(fullFolderName);
    File[] listOfFiles = folder.listFiles();
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    for (File file : listOfFiles) {
        if (file.isFile()) {
            String testFile = fullFolderName + "/" + file.getName();
            byte[] encoded = Files.readAllBytes(Paths.get(testFile));
            String fileContent = new String(encoded, StandardCharsets.UTF_8);
            te3inputText.add(fileContent);
            Document document = builder.parse(new InputSource(new StringReader(fileContent)));
            Element rootElement = document.getDocumentElement();
            NodeList nodeList = rootElement.getChildNodes();
            for (int i = 0; i < nodeList.getLength(); i++) {
                Node currentNode = nodeList.item(i);
                if (currentNode.getNodeName().equals("TEXT")) {
                    testText.add(currentNode.getTextContent());
                }
                if (currentNode.getNodeName().indexOf("DOCID") != -1) {
                    docIDs.add(currentNode.getTextContent());
                }
                if (currentNode.getNodeName().indexOf("DCT") != -1) {
                    Node dctNode = currentNode.getChildNodes().item(0);
                    NamedNodeMap dctAttrs = dctNode.getAttributes();
                    for (int j = 0; j < dctAttrs.getLength(); j++) {
                        if (dctAttrs.item(j).getNodeName().equals("value")) {
                            DCTs.add(dctAttrs.item(j).getNodeValue());
                        }
                    }
                }
            }
        }
    }
}

From source file:lv.semti.morphology.attributes.AttributeValues.java

public AttributeValues(Node node) {
     NodeList nodes = node.getChildNodes();

     for (int i = 0; i < nodes.getLength(); i++) {
         if (nodes.item(i).getNodeName().equals("Attributes"))
             for (int j = 0; j < nodes.item(i).getAttributes().getLength(); j++) {
                 Node n = nodes.item(i).getAttributes().item(j);
                 addAttribute(n.getNodeName().replaceAll("_", " "), n.getTextContent());
             }/*from   ww w. ja  va 2s  .  com*/
     }
 }