Example usage for org.jdom2.input SAXBuilder SAXBuilder

List of usage examples for org.jdom2.input SAXBuilder SAXBuilder

Introduction

In this page you can find the example usage for org.jdom2.input SAXBuilder SAXBuilder.

Prototype

public SAXBuilder() 

Source Link

Document

Creates a new JAXP-based SAXBuilder.

Usage

From source file:gestetu05.GestionnaireUtilisateur.java

List<String> LireXML(String NomFichier) {
    List<String> ListeUtilisateur = new ArrayList<>();
    //On cre une instance de SAXBuilder
    SAXBuilder sxb = new SAXBuilder();
    try {//from  w w w . j  av a 2 s . c  o m
        //On cre un nouveau document JDOM avec en argument le fichier XML
        //Le parsing est termin ;)
        document = sxb.build(new File(NomFichier));
    } catch (JDOMException | IOException e) {
    }

    //On initialise un nouvel lment racine avec l'lment racine du document.
    racine = document.getRootElement();
    //On cre une List contenant tous les noeuds "utilisateur" de l'Element racine
    List listUtilisateurs = racine.getChildren("utilisateur");
    //On cre un Iterator sur notre liste
    Iterator i = listUtilisateurs.iterator();

    while (i.hasNext()) {
        //On recre l'Element courant  chaque tour de boucle afin de
        //pouvoir utiliser les mthodes propres aux Element comme :
        //slectionner un nud fils, modifier du texte, etc...
        Element courant = (Element) i.next();
        //On affiche le nom de llment courant
        ListeUtilisateur.add(courant.getChild("nom").getText());
        ListeUtilisateur.add(courant.getChild("MotDePasse").getText());
        ListeUtilisateur.add(courant.getChild("Profession").getText());

    }
    System.out.println(ListeUtilisateur);
    return ListeUtilisateur;
}

From source file:gestetu05.GestionnaireUtilisateur.java

int AjouterUtilisateur(List<String> AjoutUtilisateur, String NomFichier) {
    List<String> ListeUtilisateur = new ArrayList<>();
    ListeUtilisateur = LireXML(NomFichier);
    int resultatAjout = 0;

    //On cre une instance de SAXBuilder
    SAXBuilder sxb = new SAXBuilder();
    try {/*from w  w  w  .j a v  a 2 s  .co m*/
        //On cre un nouveau document JDOM avec en argument le fichier XML
        //Le parsing est termin ;)
        document = sxb.build(new File(NomFichier));
    } catch (JDOMException | IOException e) {
    }

    //On initialise un nouvel lment racine avec l'lment racine du document.
    racine = document.getRootElement();
    //On cre une List contenant tous les noeuds "utilisateur" de l'Element racine
    List listUtilisateurs = racine.getChildren("utilisateur");
    //On cre un Iterator sur notre liste
    Iterator i = listUtilisateurs.iterator();

    while (i.hasNext()) {
        //On recre l'Element courant  chaque tour de boucle afin de
        //pouvoir utiliser les mthodes propres aux Element comme :
        //slectionner un nud fils, modifier du texte, etc...
        Element courant = (Element) i.next();
        //On affiche le nom de llment courant
        if (courant.getChild("nom").getText().equals(AjoutUtilisateur.get(0))) {
            resultatAjout = 0;
            System.out.println("Utlisateur dj prsent");
            break;
        } else {
            resultatAjout = 1;
        }
    }

    if (resultatAjout == 1) {

        ListeUtilisateur.add(AjoutUtilisateur.get(0));
        ListeUtilisateur.add(AjoutUtilisateur.get(1));
        ListeUtilisateur.add(AjoutUtilisateur.get(2));
        System.out.println(ListeUtilisateur);
        EcrireFichierXML(ListeUtilisateur);
        enregistreXML("Exercice.xml");
    }
    return resultatAjout;
}

From source file:gestores.IOMapeadorURLs.java

public static MapeadorDeURLs importarMapeadorSAX(String URL) {
    MapeadorDeURLs mapeador = new MapeadorDeURLs();

    SAXBuilder builder = new SAXBuilder();

    File file = new File(URL);

    try {/*from   w ww. j a v a 2s. c o  m*/
        Document document = builder.build(file);

        Element rootNode = document.getRootElement();

        List<Element> lista = rootNode.getChildren(Configuracion.marcaMapeoMapeador);

        for (Element elemento : lista) {
            String URLMapeada = elemento.getChildText(Configuracion.marcaURLMapeador);
            int map = Integer.parseInt(elemento.getChildText(Configuracion.marcaMappingMapeador));

            mapeador.agregarURL(URLMapeada, map);
        }
    } catch (Exception e) {
        System.out.println("Error al intentar leer el mapeador desde la URL: " + URL);
        e.printStackTrace();
        return null;
    }

    return mapeador;
}

From source file:gestores.IOVocabularioGeneral.java

private static ArrayList<EntradaVocabularioGeneral> importarEntradasDeVocabularioSAX(String URL) {
    ArrayList<EntradaVocabularioGeneral> entradas = new ArrayList<>();

    SAXBuilder builder = new SAXBuilder();

    File file = new File(URL);

    try {//from   w ww.  ja  v a  2 s.  com
        Document document = builder.build(file);

        Element rootNode = document.getRootElement();

        List<Element> lista = rootNode.getChildren(Configuracion.marcaEntradaVocabulario);

        for (Element elemento : lista) {

            EntradaVocabularioGeneral entrada = new EntradaVocabularioGeneral();
            entrada.setDocumentosEnQueAparece(
                    Integer.parseInt(elemento.getChildText(Configuracion.marcaCantidadDocumentosVocabulario)));
            entrada.setFrecuencia(
                    Integer.parseInt(elemento.getChildText(Configuracion.marcaFrecuenciaVocabulario)));
            entrada.setFrecuenciaMaxima(
                    Integer.parseInt(elemento.getChildText(Configuracion.marcaFrecuenciaMaximaVocabulario)));
            entrada.setPalabra((elemento.getChildText(Configuracion.marcaPalabraVocabulario)));

            entradas.add(entrada);
        }
    } catch (Exception e) {
        System.out.println("Error al intentar leer el vocabulario desde la URL: " + URL);
        e.printStackTrace();
        return new ArrayList<>();
    }

    return entradas;
}

From source file:gov.nasa.jpl.mudrod.main.MudrodEngine.java

License:Apache License

/**
 * Load the configuration provided at <a href=
 * "https://github.com/mudrod/mudrod/blob/master/core/src/main/resources/config.xml">config.xml</a>.
 *
 * @return a populated {@link java.util.Properties} object.
 *///  www .  j ava2 s  .com
public Properties loadConfig() {
    SAXBuilder saxBuilder = new SAXBuilder();

    InputStream configStream = locateConfig();

    Document document;
    try {
        document = saxBuilder.build(configStream);
        Element rootNode = document.getRootElement();
        List<Element> paraList = rootNode.getChildren("para");

        for (int i = 0; i < paraList.size(); i++) {
            Element paraNode = paraList.get(i);
            String attributeName = paraNode.getAttributeValue("name");
            if (MudrodConstants.SVM_SGD_MODEL.equals(attributeName)) {
                props.put(attributeName, decompressSVMWithSGDModel(paraNode.getTextTrim()));
            } else {
                props.put(attributeName, paraNode.getTextTrim());
            }
        }
    } catch (JDOMException | IOException e) {
        LOG.error("Exception whilst retrieving or processing XML contained within 'config.xml'!", e);
    }
    return getConfig();

}

From source file:gov.nih.nci.restgen.codegen.RESTfulResourceGenerator.java

License:BSD License

private String generateMethodEJB(String resourceName, Method method, String methodName, StringTemplate template)
        throws GeneratorException {
    Implementation impl = method.getImplementation();

    template.setAttribute("MethodName", methodName);
    template.setAttribute("ResourceName", resourceName);

    JarFile jarFile = null;/*from  w  ww  .  j av  a 2s.  c  o m*/
    org.jdom2.Document doc = null;
    try {
        jarFile = new JarFile(context.getMapping().getOptions().getEjbLocation());
        JarEntry jarEntry = jarFile.getJarEntry("META-INF/ejb-jar.xml");
        if (jarEntry != null) {
            InputStream is = jarFile.getInputStream(jarEntry);
            SAXBuilder sax = new SAXBuilder();
            doc = sax.build(is);

        } else
            throw new GeneratorException("Invalid EJB JAR path. Unable to load ejb-jar.xml");
    } catch (IOException e) {
        throw new GeneratorException("Failed to load EJB JAR. ", e);
    } catch (JDOMException e) {
        throw new GeneratorException("Failed to load EJB JAR ejb-jar.xml ", e);
    }

    org.jdom2.Element root = doc.getRootElement();

    org.jdom2.Element eBeans = root.getChild("enterprise-beans", root.getNamespace());
    List<org.jdom2.Element> sessionBeans = eBeans.getChildren("session", root.getNamespace());
    String ejbHomeName = null;
    String ejbRemoteName = null;

    boolean foundService = false;
    for (org.jdom2.Element sessionBean : sessionBeans) {
        org.jdom2.Element ejbName = sessionBean.getChild("ejb-name", root.getNamespace());

        if (ejbName.getValue().equals(impl.getName())) {
            foundService = true;
            org.jdom2.Element ejbHome = sessionBean.getChild("home", root.getNamespace());
            ejbHomeName = ejbHome.getValue();
            org.jdom2.Element ejbRemote = sessionBean.getChild("remote", root.getNamespace());
            ejbRemoteName = ejbRemote.getValue();
            break;
        }
    }

    if (!foundService)
        throw new GeneratorException("Unable to find EJB from ejb-jar.xml for " + impl.getName());

    String returnType = getOperationReturnType(impl);
    if (!returnType.equals("void")) {
        template.setAttribute("ReturnTypeNotVoid", true);
        template.setAttribute("PostReturnType", returnType);
        template.setAttribute("PutReturnType", returnType);
        template.setAttribute("DeleteReturnType", returnType);
    } else {
        template.setAttribute("ReturnTypeResponse", true);
        template.setAttribute("PostReturnType", "Response");
        template.setAttribute("PutReturnType", "Response");
        template.setAttribute("DeleteReturnType", "Response");

    }

    template.setAttribute("ReturnType", returnType);
    String pathParamPath = getOperationPath(impl, method.getName());
    if (pathParamPath != null) {
        template.setAttribute("PathParamPath", "@Path(\"" + pathParamPath + "\")");
        template.setAttribute("PathParamPathShort", pathParamPath);
    }

    template.setAttribute("PathParam", getOperationPathParams(method, impl));
    template.setAttribute("HomeInterface", ejbHomeName);
    template.setAttribute("RemoteInterface", ejbRemoteName);
    template.setAttribute("OperationName", impl.getOperation().getName());
    String operationParams = getOperationParams(impl);
    //if (operationParams != null)
    //   operationParams = operationParams + ", ";
    template.setAttribute("OperationParameters", operationParams);
    template.setAttribute("RequestType", getRequestTypes(impl));
    template.setAttribute("OperationParamNames", getOperationParams(impl));

    if (impl.getClientType().equals(Implementation.EJB_REMOTE)) {
        String jndiPath = impl.getJndiProperties();
        String fileName = jndiPath.substring(jndiPath.lastIndexOf(File.separator) + 1);
        template.setAttribute("JNDIProperties", fileName);
    }
    template.setAttribute("JNDIName", impl.getJndiName());
    return template.toString();
}

From source file:helpers.XMLParser.java

public static ParsedSingleXML parseSingleDoc(String xml) {
    ParsedSingleXML doc = null;/*from w  w  w .j a va  2s  .  c om*/
    try {

        SAXBuilder saxBuilder = new SAXBuilder();
        Document document = saxBuilder.build(new StringReader(xml));

        Element root = document.getRootElement();
        List<Attribute> rootAttributes = root.getAttributes();
        doc = new ParsedSingleXML(root.getName());
        for (Attribute attr : rootAttributes) {
            doc.addAttr(attr.getName(), attr.getValue());
        }

        XMLRow row;

        List<Element> rootChildren = root.getChildren();
        List<Element> tempChildren;
        List<Attribute> tempAttributes;

        for (Element child : rootChildren) {

            tempChildren = child.getChildren();
            row = new XMLRow(child.getName());
            tempAttributes = child.getAttributes();
            for (Attribute attr : tempAttributes) {
                row.addRootAttr(attr.getName(), attr.getValue());
            }

            for (Element tChild : tempChildren) {
                row.addRowElement(tChild.getName(), tChild.getValue());
            }

            doc.addRow(row);
        }

    } catch (JDOMException ex) {
        Logger.getLogger(XMLParser.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(XMLParser.class.getName()).log(Level.SEVERE, null, ex);
    }

    return doc;

}

From source file:helpers.XMLParser.java

public static LinkedList<ParsedSingleXML> parseMultipleDoc(String xml) {

    LinkedList<ParsedSingleXML> output = new LinkedList<>();
    ParsedSingleXML doc = null;/*from  w  w w  .  j  av  a2 s . c o m*/
    try {

        SAXBuilder saxBuilder = new SAXBuilder();
        Document document = saxBuilder.build(new StringReader(xml));

        Element root = document.getRootElement();

        List<Element> rootChildren = root.getChildren();

        for (Element child : rootChildren) {
            System.out.println(child.toString());
            output.addLast(parseSingleDoc(child.toString()));

        }

    } catch (Exception ex) {
        //return new LinkedList<>();
    }
    return output;

}

From source file:Hibernate.Util.HibernateUtil.java

private static org.w3c.dom.Document Configuracion(String dataBaseName, String userName, String password)
        throws FileNotFoundException, JDOMException, IOException {

    Document documentJDOM = new SAXBuilder().build(xmlFileURL);
    XPathExpression<Element> xPathExpression = XPathFactory.instance()
            .compile("/hibernate-configuration/session-factory/property", Filters.element());
    List<Element> elementList = xPathExpression.evaluate(documentJDOM);
    //Esto es relativo a en que posicin aparecen las lineas en el hibernate.cfg.xml
    elementList.get(2).setText(dataBaseName);
    elementList.get(3).setText(userName);
    elementList.get(4).setText(password);
    DOMOutputter domOutputter = new DOMOutputter();
    return domOutputter.output(documentJDOM);
}

From source file:hintahaku.Asetukset.java

public static void avaa() {
    Document xml;/*from  w w w  .  ja  v  a2  s .c  o  m*/
    try (BufferedReader reader = Files.newBufferedReader(tiedosto)) {
        xml = new SAXBuilder().build(reader);
    } catch (JDOMException | IOException ex) {
        return;
    }
    Element juuri = xml.getRootElement();

    if (!"Hintahaku-asetukset".equals(juuri.getAttributeValue("info"))) {
        return;
    }

    try {
        suodatintiedosto = Paths.get(juuri.getChildText("suodatintiedosto"));
    } catch (InvalidPathException | NullPointerException ex) {
    }
    try {
        viimeisinSuodatinKansio = Paths.get(juuri.getChildText("viimeisinSuodatinKansio"));
    } catch (InvalidPathException | NullPointerException ex) {
    }
    try {
        viimeisinKokoonpanoKansio = Paths.get(juuri.getChildText("viimeisinKokoonpanoKansio"));
    } catch (InvalidPathException | NullPointerException ex) {
    }
}