Example usage for org.w3c.dom Document getElementsByTagName

List of usage examples for org.w3c.dom Document getElementsByTagName

Introduction

In this page you can find the example usage for org.w3c.dom Document getElementsByTagName.

Prototype

public NodeList getElementsByTagName(String tagname);

Source Link

Document

Returns a NodeList of all the Elements in document order with a given tag name and are contained in the document.

Usage

From source file:org.apache.streams.gnip.powertrack.ActivityXMLActivitySerializer.java

private String setContentIfEmpty(String xml) throws Exception {
    DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    InputSource is = new InputSource(new StringReader(xml));
    Document doc = docBuilder.parse(is);
    doc.getDocumentElement().normalize();
    Element base = (Element) doc.getElementsByTagName("entry").item(0);
    NodeList nodeList = base.getChildNodes();
    //        for(int i=0; i < nodeList.getLength(); ++i) {
    //            System.out.println(nodeList.item(i).getNodeName());
    //        }/*  w  w w .  jav  a  2s .  c o  m*/
    Element obj = (Element) base.getElementsByTagName("activity:object").item(0);
    Element content = (Element) obj.getElementsByTagName("content").item(0);
    //        System.out.println("Number of child nodes : "+content.getChildNodes().getLength());
    //        System.out.println("Text content before : "+content.getTextContent());
    if (content.getTextContent() == null || content.getTextContent().equals("")) {
        content.setTextContent(" ");
    }
    //        System.out.println("Number of child nodes after : "+content.getChildNodes().getLength());
    //        System.out.println("Text content after : "+content.getTextContent());
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    StringWriter writer = new StringWriter();
    transformer.transform(new DOMSource(doc), new StreamResult(writer));
    String output = writer.getBuffer().toString().replaceAll("\n|\r", "");
    //        System.out.println(output);
    //        System.out.println(output);
    //        System.out.println(content);
    return output;
}

From source file:fr.paris.lutece.plugins.mylutece.modules.oauth.authentication.XMLCredentialRetriever.java

/**
 *
 *{@inheritDoc}/*w  w w. j  ava 2s .  c om*/
 */
public void doRetrieveUserInfo(HttpResponse httpResponse, OAuthUser user) {
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(httpResponse.getEntity().getContent());

        for (Entry<String, String[]> entry : getTags().entrySet()) {
            for (String strTag : entry.getValue()) {
                NodeList nodeList = doc.getElementsByTagName(strTag);

                if ((nodeList != null) && (nodeList.getLength() > 0)) {
                    String strValue = nodeList.item(0).getFirstChild().getNodeValue();

                    if (AppLogService.isDebugEnabled()) {
                        AppLogService.debug("Retrieved " + strValue + " for " + entry.getKey());
                    }

                    user.setUserInfo(entry.getKey(), strValue);

                    if (entry.getKey().equals(LuteceUser.NAME_FAMILY)) {
                        user.setName(strValue);
                    }

                    break; // no need to find other values
                }
            }
        }
    } catch (SAXException e) {
        AppLogService.error(e.getMessage(), e);
    } catch (ParserConfigurationException e) {
        AppLogService.error(e.getMessage(), e);
    } catch (IllegalStateException e) {
        AppLogService.error(e.getMessage(), e);
    } catch (IOException e) {
        AppLogService.error(e.getMessage(), e);
    }
}

From source file:minecrunch_launcher.Client.java

public void Modprofile()
        throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
    if (os.contains("Windows")) {
        minecrunchDir = home + "\\.minecrunch\\resources\\";
    } else {/*ww w . j  a  va2  s .  c  o m*/
        minecrunchDir = home + "/.minecrunch/resources/";
    }

    // Reading selected modpack profile and getting parameters
    DocumentBuilderFactory Factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = Factory.newDocumentBuilder();
    Document doc = builder.parse(minecrunchDir + name + "_profile.xml");
    doc.getDocumentElement().normalize();

    NodeList nodes = doc.getElementsByTagName("profile");
    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        if ((node.getNodeType() == Node.ELEMENT_NODE)) {
            Element element = (Element) node;
            version = element.getElementsByTagName("version").item(0).getTextContent();
            System.out.println("Forge version: " + version);
            java = element.getElementsByTagName("java").item(0).getTextContent();
            System.out.println("JVM Argument: " + java);
        }
    }
}

From source file:com.nanocrawler.contentparser.HtmlContentParser.java

private Document parseHtml(Page page, HtmlContent c) throws SAXException, IOException {
    String html;// www. j a  v  a2 s  . co  m

    // Handle char type conversions based on the byte stream, not based on what the server says
    UniversalDetector detector = new UniversalDetector(null);
    detector.handleData(page.getContentData(), 0, page.getContentData().length);
    detector.dataEnd();
    String encoding = detector.getDetectedCharset();

    if (encoding != null) {
        page.setContentCharset(encoding);
        try {
            html = new String(page.getContentData(), encoding);
        } catch (Exception ex) {
            html = new String(page.getContentData());
        }
    } else {
        html = new String(page.getContentData());
    }

    html = html.trim();
    c.setHtml(html);

    HtmlDocumentBuilder builder = new HtmlDocumentBuilder();
    builder.setCommentPolicy(XmlViolationPolicy.ALTER_INFOSET);
    builder.setContentNonXmlCharPolicy(XmlViolationPolicy.ALTER_INFOSET);
    builder.setContentSpacePolicy(XmlViolationPolicy.ALTER_INFOSET);
    builder.setNamePolicy(XmlViolationPolicy.ALTER_INFOSET);
    builder.setStreamabilityViolationPolicy(XmlViolationPolicy.ALTER_INFOSET);
    builder.setXmlnsPolicy(XmlViolationPolicy.ALTER_INFOSET);
    builder.setMappingLangToXmlLang(true);
    builder.setHtml4ModeCompatibleWithXhtml1Schemata(true);
    builder.setHeuristics(Heuristics.ALL);
    builder.setCheckingNormalization(false);
    builder.setDoctypeExpectation(DoctypeExpectation.NO_DOCTYPE_ERRORS);
    builder.setIgnoringComments(true);
    builder.setScriptingEnabled(true);
    builder.setXmlPolicy(XmlViolationPolicy.ALTER_INFOSET);

    Document doc = builder.parse(IOUtils.toInputStream(html));
    if (doc.getElementsByTagName(BODY_ELEMENT).getLength() == 0) {
        throw new RuntimeException("Problem parsing document - invalid HTML, no body element found");
    }

    return doc;
}

From source file:eu.optimis.mi.gui.server.XmlUtil.java

public List<MonitoringResource> getMonitoringRsModel(String xml) {
    try {/*from w w  w.  j a v  a2 s . co  m*/
        // Create a builder factory
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        Document doc = factory.newDocumentBuilder().parse(new InputSource(new StringReader(xml)));

        NodeList msList = doc.getElementsByTagName("monitoring_resource");

        ArrayList<MonitoringResource> rsList = new ArrayList<MonitoringResource>();
        for (int i = 0; i < msList.getLength(); i++) {
            MonitoringResource mdata = new MonitoringResource();
            Element ts = (Element) msList.item(i);
            Element eMetricname = (Element) ts.getElementsByTagName("metric_name").item(0);
            String sMetricname = eMetricname.getTextContent();
            mdata.setMetricName(sMetricname);

            Element eMetricvalue = (Element) ts.getElementsByTagName("metric_value").item(0);
            String sMetricvalue = eMetricvalue.getTextContent();
            mdata.setMetricValue(sMetricvalue);

            Element eMetricunit = (Element) ts.getElementsByTagName("metric_unit").item(0);
            String sMetricunit = eMetricunit.getTextContent();
            mdata.setMetricUnit(sMetricunit);

            Element eMetrictp = (Element) ts.getElementsByTagName("metric_timestamp").item(0);
            String tsLangType = eMetrictp.getTextContent();
            mdata.setMetricTimestamp(tsLangType);

            Element eMinfoColType = (Element) ts.getElementsByTagName("monitoring_information_collector_id")
                    .item(0);
            if (eMinfoColType != null) {
                String sMinfoColType = eMinfoColType.getTextContent();
                mdata.setCollectorId(sMinfoColType);
            }

            Element eResType = (Element) ts.getElementsByTagName("resource_type").item(0);
            if (eResType != null) {
                String sResType = eResType.getTextContent();
                mdata.setResourceType(sResType);
            }

            Element ePResId = (Element) ts.getElementsByTagName("physical_resource_id").item(0);
            if (ePResId != null) {
                String sPResId = ePResId.getTextContent();
                mdata.setPhysicalResourceId(sPResId);
            }

            Element eSResId = (Element) ts.getElementsByTagName("service_resource_id").item(0);
            if (eSResId != null) {
                String sSResId = eSResId.getTextContent();
                mdata.setServiceResourceId(sSResId);
            }

            Element eVResId = (Element) ts.getElementsByTagName("virtual_resource_id").item(0);
            if (eVResId != null) {
                String sVResId = eVResId.getTextContent();
                mdata.setVirtualResourceId(sVResId);
            }
            rsList.add(mdata);
            mdata = null;
        }

        return rsList;

    } catch (SAXException e) {
        return null;
    } catch (ParserConfigurationException e) {
        return null;
    } catch (IOException e) {
        return null;
    }
}

From source file:org.freeeed.search.web.solr.SolrSearchService.java

/**
 * Parse the given DOM to SolrResult object.
 * //from   ww w . ja  va2 s  .c  o m
 * @param query
 * @param solrDoc
 * @return
 */
private SolrResult buildResult(Document solrDoc) {
    SolrResult result = new SolrResult();

    NodeList responseList = solrDoc.getElementsByTagName("result");
    Element responseEl = (Element) responseList.item(0);
    int totalSize = Integer.parseInt(responseEl.getAttribute("numFound"));

    result.setTotalSize(totalSize);

    NodeList documentsList = responseEl.getElementsByTagName("doc");

    Map<String, SolrDocument> solrDocuments = new HashMap<String, SolrDocument>();
    for (int i = 0; i < documentsList.getLength(); i++) {
        Element documentEl = (Element) documentsList.item(i);

        Map<String, List<String>> data = new HashMap<String, List<String>>();

        NodeList fieldsList = documentEl.getChildNodes();
        for (int j = 0; j < fieldsList.getLength(); j++) {
            Element field = (Element) fieldsList.item(j);
            String name = field.getAttribute("name");
            List<String> value = new ArrayList<String>();

            //multivalues
            if (field.getNodeName().equals("arr")) {
                NodeList strList = field.getChildNodes();
                for (int k = 0; k < strList.getLength(); k++) {
                    Node strNode = strList.item(k);
                    value.add(strNode.getTextContent());
                }
            } else {
                value.add(field.getTextContent());
            }

            data.put(name, value);
        }

        SolrDocument doc = solrDocumentParser.createSolrDocument(data);
        solrDocuments.put(doc.getDocumentId(), doc);
    }

    result.setDocuments(solrDocuments);

    return result;
}

From source file:com.nanocrawler.contentparser.HtmlContentParser.java

private void getLinks(List<ExtractedUrlAnchorPair> outgoingUrls, Document doc, String elementName,
        String attribName, boolean getAnchorText) {
    if (doc.getElementsByTagName(elementName).getLength() > 0) {
        NodeList nl = doc.getElementsByTagName(elementName);
        for (int i = 0; i < nl.getLength(); i++) {
            Node n = nl.item(i);/*from   w w w  .ja v a 2 s .  com*/
            if (n.hasAttributes() && n.getAttributes().getNamedItem(attribName) != null) {
                ExtractedUrlAnchorPair newUrl = new ExtractedUrlAnchorPair();
                newUrl.setHref(n.getAttributes().getNamedItem(attribName).getNodeValue().trim());
                if (getAnchorText) {
                    newUrl.setAnchor(n.getTextContent().trim());
                } else {
                    newUrl.setAnchor("");
                }

                if (newUrl.getHref().trim().length() > 0) {
                    outgoingUrls.add(newUrl);
                }
            }
        }
    }
}

From source file:com.uber.jenkins.phabricator.coverage.CoberturaXMLParser.java

private List<String> getSourceDirs(Document doc) {
    if (workspace == null) {
        return Collections.emptyList();
    }//from  w w w. ja  v a2s . c o  m

    List<String> sourceDirs = new ArrayList<String>();
    NodeList sources = doc.getElementsByTagName(TAG_NAME_SOURCE);
    for (int i = 0; i < sources.getLength(); i++) {
        Node source = sources.item(i);
        String srcDir = source.getTextContent();
        if (srcDir.contains(workspace + "/")) {
            String relativeSrcDir = srcDir.replaceFirst(workspace + "/", "");
            if (!relativeSrcDir.isEmpty()) {
                sourceDirs.add(relativeSrcDir);
            }
        }
    }
    return sourceDirs;
}

From source file:com.diversityarrays.dalclient.DalUtil.java

public static boolean visitXmlResults(String requestUrl, Document xmldoc, List<String> tagNames,
        DalResponseRecordVisitor visitor, boolean wantEmptyRecords) {
    boolean result = true;
    for (String tagName : tagNames) {
        NodeList resultNodes = xmldoc.getElementsByTagName(tagName);
        int nNodes = resultNodes.getLength();
        for (int ni = 0; ni < nNodes; ++ni) {
            Node node = resultNodes.item(ni);
            DalResponseRecord record = DalUtil.createFrom(requestUrl, node);
            if (record != null && (wantEmptyRecords || !record.isEmpty())) {
                if (!visitor.visitResponseRecord(tagName, record)) {
                    result = false;/*from  w  w w  .  j  a  v  a 2s .c o m*/
                    break;
                }
            }
        }

        if (!result) {
            break;
        }
    }
    return result;
}