Example usage for org.jdom2 Element getChildren

List of usage examples for org.jdom2 Element getChildren

Introduction

In this page you can find the example usage for org.jdom2 Element getChildren.

Prototype

public List<Element> getChildren(final String cname) 

Source Link

Document

This returns a List of all the child elements nested directly (one level deep) within this element with the given local name and belonging to no namespace, returned as Element objects.

Usage

From source file:com.init.octo.util.FindXML.java

License:Open Source License

/**
 * This method locates an XML tag or attribute based on an input string.
 * The input locator string must be in the format root.element.element or root.element.[attribute]
 *
 * @param   locator - the definition of the element you want to locate
 * @param   root - the root element of the XML structure
 *
 * @returns   String - the string we have found, or null of it wasn't found
 *//*from   www.  ja va 2s. c o  m*/

static public String findXML(String locator, Element root) {

    Element element = null;
    String retStr = null;
    StringTokenizer tokens = new StringTokenizer(locator, ".");
    String str = tokens.nextToken();

    if (tokens.countTokens() == 0) {
        locator = "root." + locator;
        tokens = new StringTokenizer(locator, ".");
        str = tokens.nextToken();
    }

    // follow the locator text element name definition down...

    element = root;

    while (tokens.hasMoreTokens()) {
        str = tokens.nextToken();

        if (str.startsWith("[")) { // an attribute has been specified
            String attName = str.substring(1, str.indexOf("]"));
            retStr = element.getAttributeValue(attName);
            element = null;
            break;
        } else {
            String[] spec = str.split(":");

            if (spec.length == 1) {
                element = element.getChild(str);
            } else {
                /** A specific member of a repeating group has been specified... **/
                Iterator<?> it = element.getChildren(spec[0]).iterator();
                int idx = 1;
                int num = 0;

                try {
                    num = Integer.parseInt(spec[1]);
                } catch (Exception x) {
                    log.warn("Bad element index [" + spec[1] + "]");
                    num = 1;
                }

                while (it.hasNext()) {
                    element = (Element) it.next();
                    if (idx == num) {
                        break;
                    }
                }

                /** If we go past the end of the list we will return the last one... **/
                /** this way the call can detect no change in the output...          **/
            }
        }
        if (element == null) {
            return (null);
        }
    }

    if (element != null) { // wasn't specified as an attribute...
        retStr = element.getTextTrim();
    }

    return (retStr);

}

From source file:com.kixeye.scout.eureka.EurekaApplication.java

License:Apache License

/**
 * Creates a new application with a parent and raw element.
 * /*w ww . j ava 2 s.  c  o m*/
 * @param parent
 * @param element
 */
protected EurekaApplication(EurekaApplications parent, Element element) {
    this.parent = parent;
    this.name = element.getChildText("name");

    for (Element instance : element.getChildren("instance")) {
        instances.add(new EurekaServiceInstanceDescriptor(this, instance));
    }
}

From source file:com.kixeye.scout.eureka.EurekaApplications.java

License:Apache License

/**
 * Creates a top level applications object.
 * /*  w  w w.  j  a va 2s . c o  m*/
 * @param element
 */
protected EurekaApplications(Element element) {
    for (Element application : element.getChildren("application")) {
        applications.add(new EurekaApplication(this, application));
    }
}

From source file:com.move.in.nantes.cars.ParkingParser.java

private static List<Parking> parseXml() {
    List<Parking> listPakings = new ArrayList<Parking>();

    try {// w w  w. j  a v a2  s  . c om
        SAXBuilder saxb = new SAXBuilder();
        File file = new File("WEB-INF/json/Parking.xml");

        Document doc = saxb.build(file);
        Element root = doc.getRootElement();
        List<Element> locations = root.getChildren("data").get(0).getChildren("element");

        for (int i = 0; i < locations.size(); i++) {
            Element elem = locations.get(i);

            if (elem.getChildText("CATEGORIE").equalsIgnoreCase("1001")) {

                String name = elem.getChild("geo").getChildText("name");

                Coordinates coordinates = getCoordinates(elem.getChildText("_l"));

                String postalCode = elem.getChildText("CODE_POSTAL");
                String city = elem.getChildText("COMMUNE");
                String address = elem.getChildText("ADRESSE");

                listPakings.add(new Parking(name, coordinates, postalCode, city, address));
            }
        }
    } catch (JDOMException ex) {
        Logger.getLogger(ParkingParser.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(ParkingParser.class.getName()).log(Level.SEVERE, null, ex);
    }
    return listPakings;
}

From source file:com.novell.ldapchai.impl.edir.NmasResponseSet.java

License:Open Source License

private static String readDisplayString(final Element questionElement, final Locale locale) {

    final Namespace XML_NAMESPACE = Namespace.getNamespace("xml", "http://www.w3.org/XML/1998/namespace");

    // someday ResoureBundle won't suck and this will be a 5 line method.

    // see if the node has any localized displays.
    final List displayChildren = questionElement.getChildren("display");

    // if no locale specified, or if no localized text is available, just use the default.
    if (locale == null || displayChildren == null || displayChildren.size() < 1) {
        return questionElement.getText();
    }/*  ww w  . j  av  a2 s  .c  o m*/

    // convert the xml 'display' elements to a map of locales/strings
    final Map<Locale, String> localizedStringMap = new HashMap<Locale, String>();
    for (final Object aDisplayChildren : displayChildren) {
        final Element loopDisplay = (Element) aDisplayChildren;
        final Attribute localeAttr = loopDisplay.getAttribute("lang", XML_NAMESPACE);
        if (localeAttr != null) {
            final String localeStr = localeAttr.getValue();
            final String displayStr = loopDisplay.getText();
            final Locale localeKey = parseLocaleString(localeStr);
            localizedStringMap.put(localeKey, displayStr);
        }
    }

    final Locale matchedLocale = localeResolver(locale, localizedStringMap.keySet());

    if (matchedLocale != null) {
        return localizedStringMap.get(matchedLocale);
    }

    // none found, so just return the default string.
    return questionElement.getText();
}

From source file:com.novell.ldapchai.impl.edir.value.nspmComplexityRules.java

License:Open Source License

private static List<Policy> readComplexityPoliciesFromXML(final String input) {
    final List<Policy> returnList = new ArrayList<Policy>();
    try {//from  w  w w. ja va 2  s .co  m
        final SAXBuilder builder = new SAXBuilder();
        final Document doc = builder.build(new StringReader(input));
        final Element rootElement = doc.getRootElement();

        final List policyElements = rootElement.getChildren("Policy");
        for (final Object policyNode : policyElements) {
            final Element policyElement = (Element) policyNode;
            final List<RuleSet> returnRuleSets = new ArrayList<RuleSet>();
            for (final Object ruleSetObjects : policyElement.getChildren("RuleSet")) {
                final Element loopRuleSet = (Element) ruleSetObjects;
                final Map<Rule, String> returnRules = new HashMap<Rule, String>();
                int violationsAllowed = 0;

                final org.jdom2.Attribute violationsAttribute = loopRuleSet.getAttribute("ViolationsAllowed");
                if (violationsAttribute != null && violationsAttribute.getValue().length() > 0) {
                    violationsAllowed = Integer.parseInt(violationsAttribute.getValue());
                }

                for (final Object ruleObject : loopRuleSet.getChildren("Rule")) {
                    final Element loopRuleElement = (Element) ruleObject;

                    final List ruleAttributes = loopRuleElement.getAttributes();
                    for (final Object attributeObject : ruleAttributes) {
                        final org.jdom2.Attribute loopAttribute = (org.jdom2.Attribute) attributeObject;

                        final Rule rule = Rule.valueOf(loopAttribute.getName());
                        final String value = loopAttribute.getValue();
                        returnRules.put(rule, value);
                    }
                }
                returnRuleSets.add(new RuleSet(violationsAllowed, returnRules));
            }
            returnList.add(new Policy(returnRuleSets));
        }
    } catch (JDOMException e) {
        LOGGER.debug("error parsing stored response record: " + e.getMessage());
    } catch (IOException e) {
        LOGGER.debug("error parsing stored response record: " + e.getMessage());
    } catch (NullPointerException e) {
        LOGGER.debug("error parsing stored response record: " + e.getMessage());
    } catch (IllegalArgumentException e) {
        LOGGER.debug("error parsing stored response record: " + e.getMessage());
    }
    return returnList;
}

From source file:com.oagsoft.grafo.util.XMLLoader.java

public static Grafo leerArchivoXml(String nomArch) {
    SAXBuilder builder = new SAXBuilder();
    Grafo g = null;/*from w w  w  .j  a  v a 2  s . co  m*/
    try {
        Document document = (Document) builder.build(new File(nomArch));
        Element rootNode = document.getRootElement();
        Element nV = rootNode.getChild("numero-vertices");
        int numVertices = Integer.parseInt(nV.getValue().trim());
        g = new Grafo(numVertices);
        Element ad = rootNode.getChild("adyacencias");
        List<Element> hijos = ad.getChildren("adyacencia");
        for (Element hijo : hijos) {
            int nIni = Integer.parseInt(hijo.getChildTextTrim("nodo-inicial"));
            int nFin = Integer.parseInt(hijo.getChildTextTrim("nodo-final"));
            g.adyacencia(nIni, nFin);
        }
        //            System.out.println("Hay " + hijos.size()+ " adyacencias");
    } catch (JDOMException | IOException ex) {
        System.out.println(ex.getMessage());
    }
    return g;
}

From source file:com.oagsoft.wazgle.tools.XMLLoader.java

public static Grafo<GraphicNode> leerArchivoXml(String nomArch) {
    SAXBuilder builder = new SAXBuilder();
    Grafo<GraphicNode> g = null;//from  w w w.ja va  2  s.  c o m
    try {
        Document document = (Document) builder.build(new File(nomArch));
        Element rootNode = document.getRootElement();
        Element nV = rootNode.getChild("numero-vertices");
        int numVertices = Integer.parseInt(nV.getValue().trim());
        g = new Grafo(numVertices);
        Element nodos = rootNode.getChild("nodos");
        List<Element> hijos = nodos.getChildren("nodo");
        for (Element hijo : hijos) {
            int id = Integer.parseInt(hijo.getChildTextTrim("id"));
            int coorX = Integer.parseInt(hijo.getChildTextTrim("coor-x"));
            int coorY = Integer.parseInt(hijo.getChildTextTrim("coor-y"));
            GraphicNode nodo = new GraphicNode(id, new Point(coorX, coorY), 10, false);
            g.adVertice(nodo);
        }
        Element adyacencias = rootNode.getChild("adyacencias");
        List<Element> ad = adyacencias.getChildren("adyacencia");
        for (Element hijo : ad) {
            int vIni = Integer.parseInt(hijo.getChildTextTrim("nodo-inicial"));
            int vFinal = Integer.parseInt(hijo.getChildTextTrim("nodo-final"));
            GraphicNode nIni = g.getVertice(vIni);
            GraphicNode nFin = g.getVertice(vFinal);

            g.adyacencia(nIni, nFin);

        }
        //            System.out.println("Hay " + hijos.size()+ " adyacencias");
    } catch (JDOMException | IOException ex) {
        System.out.println(ex.getMessage());
    }
    return g;
}

From source file:com.ohnosequences.bio4j.tools.ExtractCitationsCommentsSamples.java

License:Open Source License

public static void main(String[] args) throws FileNotFoundException, IOException, Exception {

    if (args.length != 1) {
        System.out.println("El programa espera un parametro: \n" + "1. Nombre del archivo xml a importar \n");
    } else {/*from   ww  w. j av  a 2 s .  c om*/
        File inFile = new File(args[0]);

        Map<String, String> citationsTypesMap = new HashMap<String, String>();
        Map<String, String> commentsTypesMap = new HashMap<String, String>();

        BufferedWriter citationsOutBuff = new BufferedWriter(new FileWriter(new File("citations.xml")));
        BufferedWriter commentsOutBuff = new BufferedWriter(new FileWriter(new File("comments.xml")));

        citationsOutBuff.write("<citations>\n");
        commentsOutBuff.write("<comments>\n");

        BufferedReader reader = new BufferedReader(new FileReader(inFile));
        String line = null;
        StringBuilder entryStBuilder = new StringBuilder();

        while ((line = reader.readLine()) != null) {
            if (line.trim().startsWith("<entry")) {

                while (!line.trim().startsWith("</entry>")) {
                    entryStBuilder.append(line);
                    line = reader.readLine();
                }
                //linea final del organism
                entryStBuilder.append(line);
                //System.out.println("organismStBuilder.toString() = " + organismStBuilder.toString());
                XMLElement entryXMLElem = new XMLElement(entryStBuilder.toString());
                entryStBuilder.delete(0, entryStBuilder.length());

                List<Element> referenceList = entryXMLElem.asJDomElement().getChildren("reference");
                for (Element reference : referenceList) {
                    List<Element> citationsList = reference.getChildren("citation");
                    for (Element citation : citationsList) {
                        if (citationsTypesMap.get(citation.getAttributeValue("type")) == null) {
                            XMLElement citationXML = new XMLElement(citation);
                            System.out.println("citation = " + citationXML);
                            citationsTypesMap.put(citation.getAttributeValue("type"), citationXML.toString());
                        }
                    }
                }
                List<Element> commentsList = entryXMLElem.asJDomElement().getChildren("comment");
                for (Element comment : commentsList) {
                    if (commentsTypesMap.get(comment.getAttributeValue("type")) == null) {
                        XMLElement commentXML = new XMLElement(comment);
                        System.out.println("comment = " + commentXML);
                        commentsTypesMap.put(comment.getAttributeValue("type"), commentXML.toString());
                    }
                }

            }
        }

        Set<String> keys = citationsTypesMap.keySet();
        for (String key : keys) {
            citationsOutBuff.write(citationsTypesMap.get(key));
        }

        citationsOutBuff.write("</citations>\n");
        citationsOutBuff.close();
        System.out.println("Citations file created successfully!");

        Set<String> keysComments = commentsTypesMap.keySet();
        for (String key : keysComments) {
            commentsOutBuff.write(commentsTypesMap.get(key));
        }

        commentsOutBuff.write("</comments>\n");
        commentsOutBuff.close();
        System.out.println("Comments file created successfully!");

    }
}

From source file:com.ohnosequences.bio4j.tools.uniprot.ExtractCitationsCommentsSamples.java

License:Open Source License

public static void main(String[] args) {

    if (args.length != 1) {
        System.out.println("This program expects the following parameters: \n" + "1. Input XML file \n");
    } else {/* ww w.  ja v  a 2s .  c om*/
        BufferedWriter citationsOutBuff = null;

        try {

            File inFile = new File(args[0]);

            Map<String, String> citationsTypesMap = new HashMap<String, String>();
            Map<String, String> commentsTypesMap = new HashMap<String, String>();

            citationsOutBuff = new BufferedWriter(new FileWriter(new File("citations.xml")));
            BufferedWriter commentsOutBuff = new BufferedWriter(new FileWriter(new File("comments.xml")));

            citationsOutBuff.write("<citations>\n");
            commentsOutBuff.write("<comments>\n");

            BufferedReader reader = new BufferedReader(new FileReader(inFile));
            String line = null;
            StringBuilder entryStBuilder = new StringBuilder();

            while ((line = reader.readLine()) != null) {

                if (line.trim().startsWith("<entry")) {

                    while (!line.trim().startsWith("</entry>")) {
                        entryStBuilder.append(line);
                        line = reader.readLine();
                    }
                    //linea final del organism
                    entryStBuilder.append(line);
                    //System.out.println("organismStBuilder.toString() = " + organismStBuilder.toString());
                    XMLElement entryXMLElem = new XMLElement(entryStBuilder.toString());
                    entryStBuilder.delete(0, entryStBuilder.length());

                    List<Element> referenceList = entryXMLElem.asJDomElement().getChildren("reference");
                    for (Element reference : referenceList) {
                        List<Element> citationsList = reference.getChildren("citation");
                        for (Element citation : citationsList) {
                            if (citationsTypesMap.get(citation.getAttributeValue("type")) == null) {
                                XMLElement citationXML = new XMLElement(citation);
                                System.out.println("citation = " + citationXML);
                                citationsTypesMap.put(citation.getAttributeValue("type"),
                                        citationXML.toString());
                            }
                        }
                    }
                    List<Element> commentsList = entryXMLElem.asJDomElement().getChildren("comment");
                    for (Element comment : commentsList) {
                        if (commentsTypesMap.get(comment.getAttributeValue("type")) == null) {
                            XMLElement commentXML = new XMLElement(comment);
                            System.out.println("comment = " + commentXML);
                            commentsTypesMap.put(comment.getAttributeValue("type"), commentXML.toString());
                        }
                    }

                }
            }
            Set<String> keys = citationsTypesMap.keySet();

            for (String key : keys) {
                citationsOutBuff.write(citationsTypesMap.get(key));
            }
            citationsOutBuff.write("</citations>\n");
            citationsOutBuff.close();

            System.out.println("Citations file created successfully!");
            Set<String> keysComments = commentsTypesMap.keySet();
            for (String key : keysComments) {
                commentsOutBuff.write(commentsTypesMap.get(key));
            }

            commentsOutBuff.write("</comments>\n");
            commentsOutBuff.close();

            System.out.println("Comments file created successfully!");

        } catch (Exception ex) {
            e.xprintStackTrace();
        } finally {
            try {
                citationsOutBuff.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

    }
}