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:cz.muni.fi.mir.db.service.impl.ElementServiceImpl.java

@Override
public List<Element> extractElements(Formula formula) {
    Set<Element> temp = new HashSet<>();

    org.w3c.dom.Document doc = xmlUtils.parse(formula.getXml());

    if (doc != null) {
        org.w3c.dom.NodeList nodeList = doc.getElementsByTagName("*");
        for (int i = 0; i < nodeList.getLength(); i++) {
            temp.add(EntityFactory.createElement(nodeList.item(i).getNodeName()));
        }/*ww w  .  j a v a  2s .co m*/
    }
    List<Element> result = null;

    if (formula.getElements() == null || formula.getElements().isEmpty()) {
        result = new ArrayList<>(temp.size());
    } else {
        result = new ArrayList<>(formula.getElements());
    }

    result.addAll(temp);

    return result;
}

From source file:com.example.apis.ifashion.WOEIDUtils.java

private void parseLocationLines(Document srcDoc, String name) {
    NodeList nodeList = srcDoc.getElementsByTagName(name);
    if (nodeList.getLength() > 0) {
        Node node = nodeList.item(0);
        mParsedResult.put(name, node.getTextContent());
    }/*from ww w  .j a  va  2s  . c o  m*/
}

From source file:com.axelor.apps.base.test.PrepareCsv.java

@Test
public void prepareCsv() {
    String xmlDir = System.getProperty("xmlDir");
    String csvDir = System.getProperty("csvDir");
    List<String> ignoreType = Arrays.asList("one-to-one", "many-to-many", "one-to-many");
    try {/*from w  w  w .  j a  v a 2  s  . c  o m*/
        if (xmlDir != null && csvDir != null) {
            File xDir = new File(xmlDir);
            File cDir = new File(csvDir);
            List<String[]> blankData = new ArrayList<String[]>();
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            if (xDir.isDirectory() && cDir.isDirectory()) {
                for (File xf : xDir.listFiles()) {
                    LOG.info("Processing XML: " + xf.getName());
                    List<String> fieldList = new ArrayList<String>();
                    Document doc = dBuilder.parse(xf);
                    NodeList nList = doc.getElementsByTagName("module");
                    String module = nList.item(0).getAttributes().getNamedItem("name").getNodeValue();
                    nList = doc.getElementsByTagName("entity");
                    if (nList != null) {
                        NodeList fields = nList.item(0).getChildNodes();
                        Integer count = 0;
                        String csvFileName = module + "_" + CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL,
                                xf.getName().replace(".xml", ".csv"));
                        while (count < fields.getLength()) {
                            Node field = fields.item(count);
                            NamedNodeMap attrs = field.getAttributes();
                            String type = field.getNodeName();
                            if (attrs != null && attrs.getNamedItem("name") != null
                                    && !ignoreType.contains(type)) {
                                String fieldName = attrs.getNamedItem("name").getNodeValue();
                                if (type.equals("many-to-one")) {
                                    String[] objName = attrs.getNamedItem("ref").getNodeValue().split("\\.");
                                    String refName = objName[objName.length - 1];
                                    String nameColumn = getNameColumn(xmlDir + "/" + refName + ".xml");
                                    if (nameColumn != null)
                                        fieldList.add(fieldName + "." + nameColumn);
                                    else {
                                        fieldList.add(fieldName);
                                        LOG.error("No name column found for " + refName + ", field '"
                                                + attrs.getNamedItem("name").getNodeValue() + "'");
                                    }
                                } else
                                    fieldList.add(fieldName);
                            }

                            count++;
                        }
                        cTool.csvWriter(csvDir, csvFileName, ';', StringUtils.join(fieldList, ",").split(","),
                                blankData);
                        LOG.info("CSV file prepared: " + csvFileName);
                    }
                }

            } else
                LOG.error("XML and CSV paths must be directory");
        } else
            LOG.error("Please input XML and CSV directory path");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.fluidops.iwb.wiki.WikiBot.java

/**
    * InputStream contains a document with at least one page
    * /*from  ww  w  . j  a  v a2  s . com*/
    * <code>
    * ...
    * <page pageid="15580374" ns="0" title="Main Page">
    *     <revisions>
    *        <rev revid="464887589" parentid="447996010" timestamp="2011-12-09T03:08:20Z"
    *              xml:space="preserve">
    *        Content
    *        </rev>
    *     </revisions>
    * </page>
    * ...
    * </code>
    * 
    * Content is html decoded
    * 
    * @param page
    * @return
    * @throws IOException 
    * @throws SAXException 
    */
private String parsePage(InputStream in) throws Exception {

    DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document d = documentBuilder.parse(in);

    NodeList pages = d.getElementsByTagName("page");

    if (pages == null || pages.getLength() == 0)
        throw new IllegalArgumentException("InputStream does not have the expected 'page' section");

    NodeList revs = getChild(pages.item(0), "revisions").getElementsByTagName("rev");

    if (revs.getLength() != 1)
        throw new IllegalArgumentException(
                "Page does not have the expected structure, exactly one revision expected.");

    Element rev = (Element) revs.item(0);

    return StringEscapeUtils.unescapeHtml(rev.getTextContent());

}

From source file:com.michael.feng.utils.YahooWeather4a.WOEIDUtils.java

private String getFirstMatchingWOEID(Document srcDoc) {
    Log.d("tag", "parserWOEID");

    try {//from ww  w.  j  a  va2s.c  o m
        NodeList nodeListDescription = srcDoc.getElementsByTagName("woeid");
        if (nodeListDescription.getLength() > 0) {
            Node node = nodeListDescription.item(0);
            return node.getTextContent();
        } else {
            return WOEID_NOT_FOUND;
        }
    } catch (Exception e) {
        e.printStackTrace();
        return WOEID_NOT_FOUND;
    }

}

From source file:net.neurowork.cenatic.centraldir.workers.xml.SectorXmlImporter.java

private Sector importSector(String xmlString, Integer id)
        throws ParserConfigurationException, SAXException, IOException {
    Document doc = XmlParserUtil.createDocumentFromString(xmlString);
    Sector ret = null;//  w  w  w  .  j a v a  2  s  .co  m
    NodeList nodeLst = doc.getElementsByTagName("sector");

    for (int s = 0; s < nodeLst.getLength(); s++) {
        Node fstNode = nodeLst.item(s);
        if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
            Element elPDU = (Element) fstNode;
            String code = XmlParserUtil.getAttribute(elPDU, "code");
            NodeList fstNm = elPDU.getChildNodes();
            String sectorName = null;

            if (fstNm.getLength() > 0) {
                String tmp = ((Node) fstNm.item(0)).getNodeValue();
                byte[] utf8 = tmp.getBytes("UTF-8");
                sectorName = new String(utf8, "UTF-8");

                Integer capId = AbstractXmlImporter.getId(code);
                Sector sector = null;
                try {
                    Collection<Sector> sectores = sectorService.findByName(sectorName);

                    if (sectores != null && sectores.size() > 0) {
                        sector = sectores.iterator().next();
                    } else {
                        sector = new Sector();
                        sector.setName(sectorName);
                        sectorService.save(sector);
                    }

                    if (capId != null && capId.equals(id)) {
                        ret = sector;
                    }
                } catch (ServiceException e) {
                    logger.error(e.getMessage());
                }
            }
        }
    }
    return ret;
}

From source file:WSpatern.Search.java

private void parseXML(String line) {
    files.clear();/*from   www  . j  a v  a 2  s . co  m*/
    files_Id.clear();
    try {
        org.w3c.dom.Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .parse(new InputSource(new StringReader(line)));
        NodeList response = doc.getElementsByTagName("searchResultList");
        if (response.getLength() > 0) {
            for (int i = 0; i < response.getLength(); i++) {
                Element err = (Element) response.item(i);
                files.add(err.getElementsByTagName("nume").item(0).getTextContent());
                files_Id.add(err.getElementsByTagName("idFisier").item(0).getTextContent());

            }

        }
    } catch (ParserConfigurationException ex) {
        Logger.getLogger(LoginWS.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SAXException ex) {
        Logger.getLogger(LoginWS.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(LoginWS.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:edu.pdx.konstan2.PortlandLive.responseParserFactory.java

public void parseRoutesXML(String response, HashMap<Long, Route> routesMap, Boolean includeStops) {
    try {/*from  www. jav  a 2 s .co  m*/
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();

        InputSource is = new InputSource(new StringReader(response));

        Document doc = dBuilder.parse(is);
        doc.getDocumentElement().normalize();
        NodeList nList = doc.getElementsByTagName("route");
        for (int temp = 0; temp < nList.getLength(); temp++) {
            Node nNode = nList.item(temp);
            if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                Element eElement = (Element) nNode;
                Route r = new Route(eElement, includeStops);
                routesMap.put(r.route, r);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.krawler.esp.handlers.basecampHandler.java

public static String importProjectFromBaseCampUSerChoice(String dataString, String cid, String lid,
        String docid, String lName, String ipAddress) {
    String result = "";
    String projectName = "MyProject";
    String[] projectNames = { "MyProject", "MyProject1" };
    JSONArray jobj = null;/*from w w w .j  ava 2  s  .c  o m*/
    Connection conn = null;
    int projcount = 0;
    int todoscount = 0;
    int postscount = 0;
    int milstonecount = 0;
    Locale locale = Locale.ENGLISH;
    try {
        jobj = new JSONArray(dataString);
    } catch (JSONException ex) {
    }
    try {
        String destinationDirectory = StorageHandler.GetDocStorePath() + StorageHandler.GetFileSeparator()
                + "baseCamxml";
        conn = DbPool.getConnection();
        CompanyDAO cd = new CompanyDAOImpl();
        locale = cd.getCompanyLocale(conn, cid);
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        Document doc = docBuilder
                .parse(new File(destinationDirectory + StorageHandler.GetFileSeparator() + docid + ".xml"));
        doc.getDocumentElement().normalize();
        NodeList projects = doc.getElementsByTagName("projects");
        NodeList projectList = (getElementFromNodeList(projects)).getElementsByTagName("project");
        int len = projectList.getLength();
        for (int j = 0; j < len; j++) {
            if (checkNodeType(projectList.item(j))) {
                Element project = (Element) projectList.item(j);
                if (jobj == null) {
                    break;
                }
                JSONObject projobj = checkvalidProject(jobj.getJSONObject(0).getJSONArray("projdata"),
                        project.getElementsByTagName("id").item(0).getChildNodes().item(0).getNodeValue());
                if (projobj == null) {
                    continue;
                }
                projcount++;
                String projName = project.getElementsByTagName("name").item(0).getChildNodes().item(0)
                        .getNodeValue();
                String created_on = project.getElementsByTagName("created-on").item(0).getChildNodes().item(0)
                        .getNodeValue();
                project.getElementsByTagName("last-changed-on").item(0).getChildNodes().item(0).getNodeValue();
                String status = project.getElementsByTagName("status").item(0).getChildNodes().item(0)
                        .getNodeValue();

                String projid = createProj(conn, cid, projName, created_on, status);

                NodeList userList = ((Element) project.getElementsByTagName("participants").item(0))
                        .getElementsByTagName("person");
                for (int userCount = 0; userCount < userList.getLength(); userCount++) {
                    JSONObject user = getSystemUser(jobj.getJSONObject(0).getJSONArray("userdata"),
                            userList.item(userCount).getChildNodes().item(0).getNodeValue());
                    if (user != null && !user.getString("userid").equals("")) {
                        try {
                            int stat = 3;
                            if (StringUtil.equal(lid, user.getString("userid"))) {
                                stat = 4;
                            }
                            createresource(conn, projid, user.getString("userid"), user.getString("username"),
                                    stat);
                        } catch (ServiceException ex) {
                        }
                    }
                }
                try {
                    createresource(conn, projid, lid, lName, 4);
                } catch (ServiceException ex) {
                }
                if (projobj.getString("milestone").equals("1")) {
                    project.getElementsByTagName("milestones").item(0).getChildNodes().item(0).getNodeValue();
                    NodeList milestoneList = ((Element) project.getElementsByTagName("milestones").item(0))
                            .getElementsByTagName("milestone");

                    for (int milesNo = 0; milesNo < milestoneList.getLength(); milesNo++) {
                        milstonecount++;
                        Element milestone = (Element) milestoneList.item(milesNo);
                        //                          String completedStatus = milestone.getElementsByTagName("completed").item(0).getChildNodes().item(0).getNodeValue();
                        //                          if(StringUtil.stringCompareInLowercase(completedStatus,"true")){
                        //                              String completed_on = milestone.getElementsByTagName("completed-on").item(0).getChildNodes().item(0).getNodeValue();
                        //                              String completer_id = milestone.getElementsByTagName("completed-on").item(0).getChildNodes().item(0).getNodeValue();
                        //                          }
                        String title = milestone.getElementsByTagName("title").item(0).getChildNodes().item(0)
                                .getNodeValue();
                        String mileStoneCreated_on = milestone.getElementsByTagName("created-on").item(0)
                                .getChildNodes().item(0).getNodeValue();
                        String deadline = milestone.getElementsByTagName("deadline").item(0).getChildNodes()
                                .item(0).getNodeValue();
                        String resourceid = milestone.getElementsByTagName("responsible-party-id").item(0)
                                .getChildNodes().item(0).getNodeValue();
                        //                              milestone.getElementsByTagName("responsible-party-type").item(0).getChildNodes().item(0).getNodeValue();
                        //                              milestone.getElementsByTagName("wants-notification").item(0).getChildNodes().item(0).getNodeValue();
                        NodeList commentList = ((Element) milestone.getElementsByTagName("comments").item(0))
                                .getElementsByTagName("comment");
                        String commentBody = "";
                        for (int commentcout = 0; commentcout < commentList.getLength(); commentcout++) {
                            Element comment = (Element) commentList.item(commentcout);
                            //                                   comment.getElementsByTagName("attachments-count").item(0).getChildNodes().item(0).getNodeValue();
                            //                                   comment.getElementsByTagName("author-id").item(0).getChildNodes().item(0).getNodeValue();
                            commentBody = commentBody + comment.getElementsByTagName("body").item(0)
                                    .getChildNodes().item(0).getNodeValue() + "<br>";
                            //                                   comment.getElementsByTagName("commentable-id").item(0).getChildNodes().item(0).getNodeValue();
                            //                                   comment.getElementsByTagName("commentable-type").item(0).getChildNodes().item(0).getNodeValue();
                            //                                   comment.getElementsByTagName("created-at").item(0).getChildNodes().item(0).getNodeValue();
                            //    //                                   comment.getElementsByTagName("emailed-from").item(0).getChildNodes().item(0).getNodeValue();
                            //    //                                   commentable-id
                        }
                        createTask(conn, cid, projid, title, mileStoneCreated_on, deadline, resourceid,
                                commentBody, milesNo, jobj);
                        //                              body

                    }
                }
                //                         todo-lists
                if (projobj.getString("todos").equals("1")) {
                    NodeList todo_lists = ((Element) project.getElementsByTagName("todo-lists").item(0))
                            .getElementsByTagName("todo-list");
                    for (int todosNo = 0; todosNo < todo_lists.getLength(); todosNo++) {
                        todoscount++;
                        Element todoList = (Element) todo_lists.item(todosNo);
                        todoList.getElementsByTagName("completed-count").item(0).getChildNodes().item(0)
                                .getNodeValue();
                        String des = "";
                        if (todoList.getElementsByTagName("description").item(0).getChildNodes()
                                .item(0) != null) {
                            des = todoList.getElementsByTagName("description").item(0).getChildNodes().item(0)
                                    .getNodeValue();
                        }
                        //                             todoList.getElementsByTagName("milestone-id").item(0).getChildNodes().item(0).getNodeValue();
                        String name = todoList.getElementsByTagName("name").item(0).getChildNodes().item(0)
                                .getNodeValue();
                        todoList.getElementsByTagName("position").item(0).getChildNodes().item(0)
                                .getNodeValue();
                        todoList.getElementsByTagName("tracked").item(0).getChildNodes().item(0).getNodeValue();
                        todoList.getElementsByTagName("uncompleted-count").item(0).getChildNodes().item(0)
                                .getNodeValue();
                        String toDoStatus = todoList.getElementsByTagName("complete").item(0).getChildNodes()
                                .item(0).getNodeValue();

                        //NodeList todo_items = todoList.getElementsByTagName("todo-items");
                        //                             Connection conn,String des,String parentid,JSONArray userMap,String status,boolean group,String assignedTo,String userid
                        String assignedTo = "";
                        String parentid = createTodo(conn, name, des, "", jobj, toDoStatus, false, assignedTo,
                                lid, projid);
                        NodeList todo_items = ((Element) todoList.getElementsByTagName("todo-items").item(0))
                                .getElementsByTagName("todo-item");

                        for (int todoitemsNo = 0; todoitemsNo < todo_items.getLength(); todoitemsNo++) {
                            todoscount++;
                            Element todoitem = (Element) todo_items.item(todoitemsNo);
                            toDoStatus = todoitem.getElementsByTagName("completed").item(0).getChildNodes()
                                    .item(0).getNodeValue();
                            des = todoitem.getElementsByTagName("content").item(0).getChildNodes().item(0)
                                    .getNodeValue();
                            todoitem.getElementsByTagName("created-on").item(0).getChildNodes().item(0)
                                    .getNodeValue();
                            todoitem.getElementsByTagName("position").item(0).getChildNodes().item(0)
                                    .getNodeValue();
                            todoitem.getElementsByTagName("todo-list-id").item(0).getChildNodes().item(0)
                                    .getNodeValue();
                            if (todoitem.getElementsByTagName("responsible-party-id").item(0) != null) {
                                assignedTo = todoitem.getElementsByTagName("responsible-party-id").item(0)
                                        .getChildNodes().item(0).getNodeValue();
                            }
                            createTodo(conn, des, des, parentid, jobj, toDoStatus, true, assignedTo, lid,
                                    projid);
                        }
                    }
                }
                if (projobj.getString("post").equals("1")) {
                    NodeList posts = ((Element) project.getElementsByTagName("posts").item(0))
                            .getElementsByTagName("post");
                    //                         topic_id, group_id, topic_title, topic_poster, post_time, post_subject,post_text, ifread,flag

                    for (int postNo = 0; postNo < posts.getLength(); postNo++) {
                        postscount++;
                        Element singlePost = (Element) posts.item(postNo);
                        String PostAuthId = singlePost.getElementsByTagName("author-id").item(0).getChildNodes()
                                .item(0).getNodeValue();
                        String PostBody = "";
                        if (singlePost.getElementsByTagName("body").item(0).getChildNodes().item(0) != null) {
                            PostBody = singlePost.getElementsByTagName("body").item(0).getChildNodes().item(0)
                                    .getNodeValue();
                        }
                        String PostCommentCount = singlePost.getElementsByTagName("comments-count").item(0)
                                .getChildNodes().item(0).getNodeValue();
                        String postedon = singlePost.getElementsByTagName("posted-on").item(0).getChildNodes()
                                .item(0).getNodeValue();
                        String posttitle = "[Basecamp] " + singlePost.getElementsByTagName("title").item(0)
                                .getChildNodes().item(0).getNodeValue();
                        String topicid = insertDiscussionTopic(conn, projid, posttitle, PostAuthId, postedon,
                                PostBody, jobj, lid);

                        NodeList subPosts = ((Element) singlePost.getElementsByTagName("comments").item(0))
                                .getElementsByTagName("comment");
                        for (int subPostCount = 0; subPostCount < subPosts.getLength(); subPostCount++) {
                            postscount++;
                            Element subPost = (Element) subPosts.item(subPostCount);
                            String subpostAuthid = subPost.getElementsByTagName("author-id").item(0)
                                    .getChildNodes().item(0).getNodeValue();
                            String subpostBody = "";
                            if (subPost.getElementsByTagName("body").item(0).getChildNodes().item(0) != null) {
                                subpostBody = subPost.getElementsByTagName("body").item(0).getChildNodes()
                                        .item(0).getNodeValue();
                            }
                            String subpostCreatedat = subPost.getElementsByTagName("created-at").item(0)
                                    .getChildNodes().item(0).getNodeValue();
                            insertDiscussionSubPost(conn, projid, posttitle, subpostAuthid, subpostCreatedat,
                                    subpostBody, jobj, lid, topicid);
                        }

                    }
                }
                String userFullName = AuthHandler.getAuthor(conn, lid);
                String params = userFullName + "(" + lName + ")," + projName;
                AuditTrail.insertLog(conn, "325", lid, lid, projid, cid, params, ipAddress, 0);
            }
            //                    }
        }
        result = String.format(
                MessageSourceProxy.getMessage("pm.admin.project.basecamp.importsuccess", null, locale),
                projcount, milstonecount, todoscount, postscount);
        conn.commit();
    } catch (Exception ex) {
        KrawlerLog.op.warn("Problem Occured while importing projects from base camp from " + ex.toString());
        DbPool.quietRollback(conn);
        result = MessageSourceProxy.getMessage("pm.project.basecamp.fileerror", null, locale);
    } finally {
        DbPool.quietClose(conn);
    }
    return result;
}

From source file:edu.pdx.konstan2.PortlandLive.responseParserFactory.java

public void parseStopsXML(String response, HashMap<LatLng, Stop> sMap) {
    try {//from www .ja  v a  2s .  co m
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();

        InputSource is = new InputSource(new StringReader(response));

        Document doc = dBuilder.parse(is);
        doc.getDocumentElement().normalize();
        NodeList nList = doc.getElementsByTagName("location");
        for (int temp = 0; temp < nList.getLength(); temp++) {
            Node nNode = nList.item(temp);
            if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                Element eElement = (Element) nNode;
                Stop t = new Stop(eElement);
                sMap.put(new LatLng(t.latitude, t.longitude), t);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}