Example usage for org.dom4j Node selectNodes

List of usage examples for org.dom4j Node selectNodes

Introduction

In this page you can find the example usage for org.dom4j Node selectNodes.

Prototype

List<Node> selectNodes(String xpathExpression);

Source Link

Document

selectNodes evaluates an XPath expression and returns the result as a List of Node instances or String instances depending on the XPath expression.

Usage

From source file:data.BookshareWS.java

@Override
public void parse(String tekst) throws Exception {
    try {/*ww w .j a v  a  2 s. c o  m*/
        //List<Book> lista=new ArrayList<>();
        Document document = DocumentHelper.parseText(tekst);

        List list = document.selectNodes("//result");
        //System.out.println("Velicina liste "+list.size());
        if (list == null || list.size() == 0) {
            System.out.println("Lista je null");
            kraj = true;
        } else {
            System.out.println("Trenutni broj strana " + trenutnaStrana);
            for (int i = 0; i < list.size(); i++) {
                Book b = new Book();
                b.setUri(URIGenerator.generateUri(b));
                Node node = (Node) list.get(i);
                b.setTitle(node.selectSingleNode("title").getText());

                Node isbn = node.selectSingleNode("isbn13");
                if (isbn != null) {
                    b.setIsbn(isbn.getText());
                }
                List autori = node.selectNodes("author");

                for (int j = 0; j < autori.size(); j++) {
                    Person p = new Person();
                    p.setUri(URIGenerator.generateUri(p));
                    p.setName(((Node) autori.get(j)).getText());
                    b.getAuthors().add(p);
                }

                Organization o = new Organization();
                o.setUri(URIGenerator.generateUri(o));
                Node publisher = node.selectSingleNode("publisher");
                if (publisher != null) {
                    o.setName(publisher.getText());
                }
                b.setPublisher(o);

                Node description = node.selectSingleNode("brief-synopsis");
                if (description != null) {
                    b.setDescription(description.getText());
                }
                lista.add(b);

            }
            trenutnaStrana++;
            //kraj=true;
        }

    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }
}

From source file:de.innovationgate.wgpublisher.webtml.Item.java

License:Open Source License

public void tmlEndTag() throws WGException, TMLException {

    String itemName = this.getName();
    TMLContext tmlContext = this.getTMLContext();
    List result = null;// ww w  .j a  v a2 s  .c  om
    String type = this.getType();

    // add warning on illegal use of highlight attribute
    if (stringToBoolean(getHighlight())) {
        if (!type.equals("content")) {
            addWarning("Highlighting can only be used with type 'content' - skipped.");
        }
    }

    // Retrieve value
    if (type.equals("content")) {
        result = tmlContext.itemlist(itemName, buildNamedActionParameters(false));
        if (stringToBoolean(getHighlight())) {
            if (this.stringToBoolean(this.getScriptlets())) {
                addWarning("Highlighting cannot be used with scriptlets - skipped.");
            } else if (this.getAliases() != null) {
                addWarning("Highlighting cannot be used with aliases - skipped.");
            } else if (getXpath() != null) {
                addWarning("Highlighting cannot be used together with xpath - skipped.");
            } else {
                // highlight itemvalue with information from lucene query
                result = Collections.singletonList(tmlContext.highlightitem(itemName, getHighlightprefix(),
                        getHighlightsuffix(), getStatus().encode));
                getStatus().encode = "none";
            }
        }
    } else if (type.equals("profile")) {
        TMLUserProfile profile = tmlContext.getprofile();
        if (profile == null) {
            this.addWarning("Current user has no profile", true);
            return;
        }
        result = profile.itemlist(itemName);
    } else if (type.equals("portlet")) {
        TMLPortlet portlet = tmlContext.getportlet();
        if (portlet == null) {
            this.addWarning("Current user has no portlet registration", true);
            return;
        }
        result = portlet.itemlist(itemName);
    } else if (type.equals("tmlform")) {
        TMLForm form = tmlContext.gettmlform();
        if (form == null) {
            addWarning("There is no current WebTML form at this position in the current request");
            return;
        }
        result = form.fieldlist(itemName);
    }

    // The item does not exist or is empty. Treat as empty list.
    if (result == null) {
        result = new ArrayList();
    }

    // Eventually execute xpath
    String xpath = getXpath();
    if (xpath != null && result.size() > 0) {
        Object firstResult = result.get(0);
        if (firstResult instanceof Node) {
            Node resultNode = (Node) firstResult;
            result = resultNode.selectNodes(xpath);
        } else if (firstResult instanceof String) {
            try {
                Document doc = DocumentHelper.parseText((String) firstResult);
                result = doc.selectNodes(xpath);
            } catch (DocumentException e) {
                addWarning("Unable to parse item content '" + itemName + "' as XML: " + firstResult);
            }
        } else if (ExpressionEngineFactory.getTMLScriptEngine()
                .determineTMLScriptType(firstResult) == RhinoExpressionEngine.TYPE_XMLOBJECT) {
            result = ExpressionEngineFactory.getTMLScriptEngine().xpathTMLScriptBean(firstResult, xpath);
        } else {
            JXPathContext jxcontext = JXPathContext.newContext(firstResult);
            Iterator jxresults = jxcontext.iterate(xpath);
            result = new ArrayList();
            while (jxresults.hasNext()) {
                result.add(jxresults.next());
            }
        }
    }

    // Eventually resolve scriptlets
    if (result.size() > 0 && this.stringToBoolean(this.getScriptlets()) == true) {
        RhinoExpressionEngine engine = ExpressionEngineFactory.getTMLScriptEngine();
        String resolvedResultStr = null;
        try {
            Map params = new HashMap();
            params.put(RhinoExpressionEngine.SCRIPTLETOPTION_LEVEL, RhinoExpressionEngine.LEVEL_SCRIPTLETS);
            resolvedResultStr = engine.resolveScriptlets(result.get(0), getTMLContext(), params);
            result = new ArrayList();
            result.add(resolvedResultStr);
        } catch (Exception e) {
            throw new TMLException("Exception parsing scriptlets", e, false);
        }
    }

    // BI-Editor (See Root-Class for attrib WGACore.ATTRIB_EDITDOCUMENT)
    Object attribEdit = this.getPageContext().getRequest().getAttribute(WGACore.ATTRIB_EDITDOCUMENT);
    if (attribEdit != null && getEditor() != null
            && attribEdit.equals(this.getTMLContext().getcontent().getContentKey().toString())) {
        buildEditor(itemName, result);
        setResult(result);
    } else {
        // if aliases are defined, replace values with aliases
        List aliases = this.retrieveAliases();
        if (aliases.isEmpty())
            this.setResult(result);
        else {
            WGA wga = WGA.get();
            this.setResult(wga.aliases(WGUtils.toString(result), aliases));
        }

    }
}

From source file:de.thischwa.pmcms.model.tool.BackupParser_1.java

License:LGPL

private void importLevel(Level parentLevel, Node levelNode) {
    Element levelElement = (Element) levelNode;
    Level level = new Level();
    level.setName(levelElement.attributeValue("name"));
    level.setTitle(levelElement.selectSingleNode("title").getText());
    level.setParent(parentLevel);/*from w  ww  . j  a v a2  s  .c o m*/
    parentLevel.add(level);

    @SuppressWarnings("unchecked")
    List<Node> pages = levelNode.selectNodes("page|gallery");
    for (Node node : pages) {
        if (node.getName().equals("page"))
            importPage(level, node);
        else
            importGallery(level, node);
    }

    @SuppressWarnings("unchecked")
    List<Node> subLevels = levelNode.selectNodes("level");
    for (Node node : subLevels) {
        importLevel(level, node);
    }
}

From source file:de.thischwa.pmcms.model.tool.BackupParser_1.java

License:LGPL

private void importGallery(Level parent, Node galleryNode) {
    Element galleryElement = (Element) galleryNode;
    Template template = templateCache.get(Integer.parseInt(galleryElement.attributeValue("templateID")));
    Template imageTemplate = templateCache
            .get(Integer.parseInt(galleryElement.attributeValue("imageTemplateID")));
    Gallery gallery = new Gallery();
    gallery.setParent(parent);//ww  w. j ava2s. co  m
    parent.add(gallery);
    gallery.setName(galleryElement.attributeValue("name"));
    if (galleryElement.selectSingleNode("title") != null
            && StringUtils.isNotBlank(galleryElement.selectSingleNode("title").getText()))
        gallery.setTitle(galleryElement.selectSingleNode("title").getText());
    gallery.setTemplate(template);
    gallery.setThumbnailMaxWidth(Integer.parseInt(galleryElement.attributeValue("thumbnailMaxWidth")));
    gallery.setThumbnailMaxHeight(Integer.parseInt(galleryElement.attributeValue("thumbnailMaxHeight")));
    gallery.setImageTemplate(imageTemplate);
    gallery.setImageMaxWidth(Integer.parseInt(galleryElement.attributeValue("imageMaxWidth")));
    gallery.setImageMaxHeight(Integer.parseInt(galleryElement.attributeValue("imageMaxHeight")));
    incProgressValue();

    @SuppressWarnings("unchecked")
    List<Node> contentNodes = galleryNode.selectNodes("content");
    fillContent(gallery, contentNodes);

    @SuppressWarnings("unchecked")
    List<Node> images = galleryElement.selectNodes("image");
    for (Node imageNode : images) {
        Element imageElement = (Element) imageNode;
        Image image = new Image();
        image.setTitle(imageElement.selectSingleNode("title").getText());
        image.setDescription(imageElement.selectSingleNode("description").getText());
        image.setFileName(imageElement.attributeValue("fileName"));
        image.setParent(gallery);
        gallery.add(image);
        incProgressValue();
    }
}

From source file:de.thischwa.pmcms.model.tool.BackupParser_1.java

License:LGPL

private void importPage(Level parent, Node pageNode) {
    Element pageElement = (Element) pageNode;
    Template template = templateCache.get(Integer.parseInt(pageElement.attributeValue("templateID")));

    Page page = new Page();
    page.setParent(parent);//ww  w . j a v a 2 s  . c  o m
    parent.add(page);
    page.setName(pageElement.attributeValue("name"));
    page.setTemplate(template);
    if (pageElement.selectSingleNode("title") != null)
        page.setTitle(pageElement.selectSingleNode("title").getText());

    incProgressValue();

    @SuppressWarnings("unchecked")
    List<Node> contentNodes = pageNode.selectNodes("content");
    fillContent(page, contentNodes);
}

From source file:de.thischwa.pmcms.model.tool.BackupParser_old.java

License:LGPL

private void importGallery(Level parent, Node galleryNode) {
    Element galleryElement = (Element) galleryNode;
    Gallery gallery = new Gallery();
    gallery.setParent(parent);/*from  ww  w. j a v a  2 s .com*/
    parent.add(gallery);
    gallery.setName(galleryElement.attributeValue("name"));
    if (galleryElement.selectSingleNode("title") != null
            && StringUtils.isNotBlank(galleryElement.selectSingleNode("title").getText()))
        gallery.setTitle(galleryElement.selectSingleNode("title").getText());
    gallery.setTemplate(templateCache.get(galleryElement.attributeValue("templateFile")));
    gallery.setThumbnailMaxWidth(Integer.parseInt(galleryElement.attributeValue("thumbnailMaxWidth")));
    gallery.setThumbnailMaxHeight(Integer.parseInt(galleryElement.attributeValue("thumbnailMaxHeight")));
    gallery.setImageTemplate(templateCache.get(galleryElement.selectSingleNode("imageTemplate").getText()));
    gallery.setImageMaxWidth(Integer.parseInt(galleryElement.attributeValue("imageMaxWidth")));
    gallery.setImageMaxHeight(Integer.parseInt(galleryElement.attributeValue("imageMaxHeight")));
    incProgressValue();

    @SuppressWarnings("unchecked")
    List<Node> contentNodes = galleryNode.selectNodes("content");
    fillContent(gallery, contentNodes);

    @SuppressWarnings("unchecked")
    List<Node> images = galleryElement.selectNodes("image");
    for (Node imageNode : images) {
        Element imageElement = (Element) imageNode;
        Image image = new Image();
        image.setTitle(imageElement.selectSingleNode("title").getText());
        image.setDescription(imageElement.selectSingleNode("description").getText());
        image.setFileName(imageElement.attributeValue("fileName"));
        image.setParent(gallery);
        gallery.add(image);
        incProgressValue();
    }
}

From source file:de.thischwa.pmcms.model.tool.BackupParser_old.java

License:LGPL

private void importPage(Level parent, Node pageNode) {
    Element pageElement = (Element) pageNode;

    Page page = new Page();
    page.setParent(parent);//from  w w w .j a  v  a2s .co  m
    parent.add(page);
    page.setName(pageElement.attributeValue("name"));
    page.setTemplate(templateCache.get(pageElement.attributeValue("templateFile")));
    if (pageElement.selectSingleNode("title") != null)
        page.setTitle(pageElement.selectSingleNode("title").getText());

    incProgressValue();

    @SuppressWarnings("unchecked")
    List<Node> contentNodes = pageNode.selectNodes("content");
    fillContent(page, contentNodes);
}

From source file:edu.jhu.cvrg.ceptools.main.PubMedSearch.java

License:Apache License

public void processUrl() throws Exception {
    searcher = "title";
    initialProcess();//  w  w  w .j av a 2  s.c  om

    SAXReader reader = new SAXReader();
    SAXReader reader2 = new SAXReader();
    Document document;

    String mytitle, myabstract, myyear, myfullname;
    Element journalname, journalyear, journalmonth, journalday, journalvolume, journalissue, journalpagestart,
            epubday, epubmonth, epubyear, pubdoi;
    int mypmid;

    List<String> mylauthors = new ArrayList<String>();
    List<String> myfauthors = new ArrayList<String>();
    List<String> myfnames = new ArrayList<String>();

    //PubMed

    if (searcher.equalsIgnoreCase("title")) {

        int counter = 1;
        document = reader.read(url);
        @SuppressWarnings("rawtypes")
        List idlist = document.selectNodes("//IdList/Id");

        @SuppressWarnings("rawtypes")
        Iterator iditer = idlist.iterator();
        String pubmedlist = "";
        int x = 0;
        this.counter = 0;

        while (iditer.hasNext()) {
            Element pelement = (Element) iditer.next();
            if (x == 0) {
                pubmedlist += pelement.getText();
                x += 1;
            } else {
                pubmedlist += "," + pelement.getText();
            }
        }

        url = base + "efetch.fcgi?db=pubmed&id=" + pubmedlist + "&retmax=200&retmode=xml&rettype=abstract";
        Document pubdoc = reader2.read(url);

        @SuppressWarnings("unchecked")
        List<Node> thelist = pubdoc.selectNodes("//PubmedArticle| //PubmedBookArticle");

        Element abstractnode, titlenode, yearsnode, pmidnode;
        @SuppressWarnings("rawtypes")
        List firstnamenode;
        @SuppressWarnings("rawtypes")
        List lastnamenode;

        for (Node currnode : thelist) {
            mylauthors = new ArrayList<String>();
            myfauthors = new ArrayList<String>();
            myfnames = new ArrayList<String>();
            epubsum = epubsum2 = authorfull = "";

            titlenode = (Element) currnode.selectSingleNode(".//ArticleTitle | .//BookTitle");
            yearsnode = (Element) currnode
                    .selectSingleNode(".//PubDate/Year | .//DateCompleted/Year | .//DateCreated/Year");
            journalname = (Element) currnode.selectSingleNode(".//Journal/Title");
            journalyear = (Element) currnode.selectSingleNode(".//PubDate/Year");
            journalmonth = (Element) currnode.selectSingleNode(".//PubDate/Month");

            journalday = (Element) currnode.selectSingleNode(".//PubDate/Day");
            journalvolume = (Element) currnode.selectSingleNode(".//JournalIssue/Volume");
            journalissue = (Element) currnode.selectSingleNode(".//JournalIssue/Issue");
            journalpagestart = (Element) currnode.selectSingleNode(".//Pagination/MedlinePgn");

            epubday = (Element) document.selectSingleNode(
                    ".//PubMedPubDate[@PubStatus='aheadofprint']/Day  | .//PubMedPubDate[@PubStatus='epublish']/Day ");
            epubmonth = (Element) document.selectSingleNode(
                    ".//PubMedPubDate[@PubStatus='aheadofprint']/Month | .//PubMedPubDate[@PubStatus='epublish']/Month");
            epubyear = (Element) document.selectSingleNode(
                    ".//PubMedPubDate[@PubStatus='aheadofprint']/Year | .//PubMedPubDate[@PubStatus='epublish']/Year");

            pubdoi = (Element) currnode.selectSingleNode(".//ArticleId[@IdType='doi']");

            firstnamenode = currnode.selectNodes(".//ForeName");
            lastnamenode = currnode.selectNodes(".//LastName");
            abstractnode = (Element) currnode.selectSingleNode(".//Abstract/AbstractText[1]");
            pmidnode = (Element) currnode.selectSingleNode(".//PMID");

            myfnames = new ArrayList<String>();
            @SuppressWarnings("rawtypes")
            Iterator fiter = firstnamenode.iterator();
            @SuppressWarnings("rawtypes")
            Iterator liter = lastnamenode.iterator();

            if (journalname != null) {
                jn = journalname.getText();
            }
            if (journalvolume != null) {
                jv = journalvolume.getText();
            }
            if (journalissue != null) {
                ji = journalissue.getText();
            }
            if (journalmonth != null) {
                jm = journalmonth.getText();
            }
            if (journalyear != null) {
                jy = journalyear.getText();
            }
            if (journalpagestart != null) {
                jsp = journalpagestart.getText();
            }
            if (journalday != null) {
                jd = journalday.getText();
            }
            if (epubday != null) {
                epday = epubday.getText();
            }
            if (epubmonth != null) {
                epmonth = epubmonth.getText();
            }
            if (epubyear != null) {
                epyear = epubyear.getText();
            }
            if (pubdoi != null) {
                doi = "doi: " + pubdoi.getText();
            }
            if (jv.length() > 0) {
                epubsum2 += jv;
            }

            if (ji.length() > 0) {
                epubsum2 += "(" + ji + ")" + ":";
            }

            if (jsp.length() > 0) {
                epubsum2 += jsp + ".";
            }

            if (epmonth.length() < 1 && epyear.length() < 1 && epday.length() < 1) {
                epubsum = "[Epub ahead of print]";
            } else if (epyear.length() > 0) {
                epubsum = "Epub " + epyear + " " + epmonth + " " + epday;
            } else {
                epubsum = "";
            }

            mytitle = titlenode.getText();
            myyear = yearsnode.getText();
            mypmid = Integer.valueOf(pmidnode.getText());

            while (fiter.hasNext()) {
                Element fname = (Element) fiter.next();
                Element lname = (Element) liter.next();

                myfauthors.add(fname.getText());
                mylauthors.add(lname.getText());

                myfullname = fname.getText() + " " + lname.getText();
                myfnames.add(myfullname);

                if (fiter.hasNext()) {
                    authorfull = authorfull + myfullname + ", ";
                } else {
                    authorfull = authorfull + myfullname;
                }

            }

            if (abstractnode != null) {
                myabstract = abstractnode.getText();
            } else {
                myabstract = "NO ABSTRACT FOUND.";
            }

            publications.add(new Publication(mytitle, myabstract, myyear, myfauthors, mylauthors, myfnames, jv,
                    jn, jy, jm, jd, jsp, ji, epday, epmonth, epyear, doi, epubsum, epubsum2, authorfull, mypmid,
                    counter));

            counter++;

        }

    }

}

From source file:edu.ku.brc.specify.toycode.L18NStringResApp.java

License:Open Source License

/**
 * @param file/*from  w w  w.j  a  v a 2 s. c o m*/
 */
public void process(final File fileArg, final boolean doDiffs) {
    try {
        String dirName = RES_PATH + "values-" + destLocale.getLanguage();
        String path = dirName + File.separator + fileArg.getName();

        File file = fileArg;
        if (doDiffs) {
            file = new File(path);
        }
        Document doc = readFileToDOM4J(new FileInputStream(file));
        Node root = doc.getRootElement();

        for (Object nodeObj : root.selectNodes("/resources/string")) {
            Node node = (Node) nodeObj;
            String name = XMLHelper.getAttr((Element) node, "name", null);

            if (doDiffs) {
                if (baseHash.get(name) != null) {
                    continue;
                }
            }

            String text = node.getText();
            String transText = translate(text);
            if (transText != null) {
                node.setText(transText);
            }
            System.out.println(name + "[" + text + "][" + transText + "]");
        }

        File dir = new File(dirName);
        if (!dir.exists()) {
            dir.mkdir();
        }

        FileOutputStream fos = new FileOutputStream(path);
        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter writer = new XMLWriter(fos, format);
        writer.write(doc);
        writer.flush();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:edu.ku.brc.specify.toycode.L18NStringResApp.java

License:Open Source License

/**
 * @param file//from  w ww. j  ava  2s.c  om
 * @param hash
 * @param index
 */
public void process(final File file, final HashMap<String, Pair<String, String>> hash, final int index) {
    try {
        Document doc = readFileToDOM4J(new FileInputStream(file));
        Node root = doc.getRootElement();

        for (Object nodeObj : root.selectNodes("/resources/string")) {
            Node node = (Node) nodeObj;
            String name = XMLHelper.getAttr((Element) node, "name", null);
            String text = node.getText();

            Pair<String, String> p = hash.get(name);
            if (p == null) {
                p = new Pair<String, String>();
                hash.put(name, p);
            }
            if (index == 0) {
                p.first = text;
            } else {
                p.second = text;
            }
        }

        if (index == 1) {
            FileOutputStream fos = new FileOutputStream(
                    FilenameUtils.getBaseName(file.getName()) + "_compare" + destLocale.getLanguage() + ".txt");
            PrintWriter pw = new PrintWriter(fos);

            Vector<String> keys = new Vector<String>(hash.keySet());
            Collections.sort(keys);
            for (String key : keys) {
                Pair<String, String> p = hash.get(key);
                pw.println(String.format("\n---- %s -----\n%s\n%s", key, chk(p.first), chk(p.second)));
            }
            pw.flush();
            pw.close();
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}