elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Estamos en la red social de Mastodon


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  Java
| | | |-+  modificar XML
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] 2 Ir Abajo Respuesta Imprimir
Autor Tema: modificar XML  (Leído 5,331 veces)
ryhuso

Desconectado Desconectado

Mensajes: 25


Ver Perfil
modificar XML
« en: 7 Mayo 2020, 15:26 pm »

Hola necesito añadir un nodo y también modificar uno existente del cual preguntare por teclado el nombre del nodo en un archivo XML, no se muy bien como hacerlo, los ejemplos que encontré están en ingles o con datos que no entiendo de donde salen.


En línea

rub'n


Desconectado Desconectado

Mensajes: 1.217


(e -> λ("live now")); tatuar -> λ("α");


Ver Perfil WWW
Re: modificar XML
« Respuesta #1 en: 7 Mayo 2020, 15:35 pm »

Q tal que es la que hay?

Pues bien, Pon lo que llevas al menos ni idea tengo un por donde vas,

Con un fichero Properties quizá quizá, valla la cuention por ahí.


En línea



rubn0x52.com KNOWLEDGE  SHOULD BE FREE.
If you don't have time to read, you don't have the time (or the tools) to write, Simple as that. Stephen ki
ryhuso

Desconectado Desconectado

Mensajes: 25


Ver Perfil
Re: modificar XML
« Respuesta #2 en: 7 Mayo 2020, 16:34 pm »

el problema me pide que pueda modificar el fichero XML y mostrarlo por pantalla
lo que tengo hecho es solo lo de mostrar por pantalla... la opcion de modificar tiene que modificar un tipo de nodo especifico por ejem: "titulo" que tenga nombre "Colonia " cambiarlo por otro

Código:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import xml.Presentar;

public class Maneja {

    public static void main(String[] args) throws TransformerException, TransformerConfigurationException {
        String nodees = "";
        Scanner entrada = new Scanner(System.in);
        System.out.println("\t\tDocumentos XML");
        int opcion = 0;
        while (opcion != 5) {
            System.out.println("\t\t\t\tMenú de Opciones");
            System.out.println("\t\t\t\t================");
            System.out.println("1)Presentar XML");
            System.out.println("2)Añadir nuevo nodo");
            System.out.println("3)Modificar nodo");
            System.out.println("4)Eliminar nodo");
            System.out.println("5)Salir");
            System.out.println("================");
            try {
                opcion = entrada.nextInt();
            } catch (Exception e) {

                entrada = new Scanner(System.in);
            }

            switch (opcion) {
                case 1:
                    Presentar p = new Presentar();
                    p.Presentar();
                    break;
                case 2:

                    break;

                case 3:
                    entrada.nextLine();
                    System.out.println("Ingresa el nodo a modificar");
                    nodees = entrada.nextLine();
                    Presentar m = new Presentar();
                    m.Modificar(nodees);
                    break;
                case 4:

                    break;
                           

                case 5:
                    System.exit(0);
                    break;
                default:
                    System.out.println("Opcion no valida");
                    break;
            }

        }
    }

}

y en otra clase tengo las funciones
Código:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import jdk.internal.org.objectweb.asm.commons.GeneratorAdapter;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 *
 * @author orlando
 */
public class Presentar {

    public void Presentar() {
        try {

            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

            DocumentBuilder builder = factory.newDocumentBuilder();

            Document documento = builder.parse(new File("peliculas.xml"));

            NodeList listaPelis = documento.getElementsByTagName("pelicula");

            for (int i = 0; i < listaPelis.getLength(); i++) {

                Node nodo = listaPelis.item(i);

                if (nodo.getNodeType() == Node.ELEMENT_NODE) {

                    Element e = (Element) nodo;

                    NodeList hijos = e.getChildNodes();

                    for (int j = 0; j < hijos.getLength(); j++) {

                        Node hijo = hijos.item(j);

                        if (hijo.getNodeType() == Node.ELEMENT_NODE) {

                            System.out.println(hijo.getNodeName() + ":  " + hijo.getTextContent());
                        }

                    }
                    System.out.println("----------------------------------------------");
                }

            }

        } catch (ParserConfigurationException | SAXException | IOException ex) {
            System.out.println(ex.getMessage());
        }
    }

    public void Añadir() {

    }

    public void Modificar(String nodoModificar) {
        File fichXML = new File("peliculas.xml");
        try {

            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            Document doc = docBuilder.parse(fichXML);

            doc.getDocumentElement().normalize();

            Node nDam = doc.getFirstChild();

            NodeList nPelis = nDam.getChildNodes();
            for (int cont1N = 0; cont1N < nPelis.getLength(); cont1N++) {

                Node cadaC = nPelis.item(cont1N);

                NodeList nTitulo = cadaC.getChildNodes();
                for (int cont2N = 0; cont2N < nTitulo.getLength(); cont2N++) {

                    Node cadaPeli = nTitulo.item(cont2N);

                    if (nodoModificar.equals(cadaPeli.getNodeName())) {
                        System.out.println("Ingresa el valor del nodo seleccionado que deseas cambiar");
                        Scanner entrada = new Scanner(System.in);
                        String n = entrada.nextLine();
                        if (n.equals(cadaPeli.getNodeValue())) {
                            System.out.println("Ingresa la nueva informacion del nodo"); 
                            String m = entrada.nextLine();
                             nTitulo.item(cont2N).setTextContent(m);
                        }
                    }
                }
            }

            TransformerFactory factoriaTransf = TransformerFactory.newInstance();
            Transformer transformador = factoriaTransf.newTransformer();
            DOMSource source = new DOMSource(doc);

            StreamResult consoleResult = new StreamResult(System.out);
            transformador.transform(source, consoleResult);

            StreamResult fileResult = new StreamResult(new File("peliculas.xml"));
            transformador.transform(source, fileResult);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void eliminar() {

       
    }

}
En línea

rub'n


Desconectado Desconectado

Mensajes: 1.217


(e -> λ("live now")); tatuar -> λ("α");


Ver Perfil WWW
Re: modificar XML
« Respuesta #3 en: 8 Mayo 2020, 04:54 am »

Hice un Builder, debes invocar a la primera opción si no esta creado el archivo, opcion 0

Para crear usar numero 0
Código
  1. /**
  2. * Instanciando Builder para crear Elemento Root e hijos
  3. */
  4.     new Presentar.Builder()
  5.            .conDocument(BuilderFile.CREATE)
  6.            .conRootElement(TIENDA)
  7.            .conId("1")
  8.            .createNodeAndChild(PELICULA, "titulo", "Rambo 1")
  9.            .conId("2")
  10.            .createNodeAndChild(PELICULA, "titulo", "Rambo 2")
  11.            .build();

Para modificar el fichero usa

viejoNombre = Rambo 2
nuevoNombre= Rambo 2 la resurrecion

Código
  1. new Presentar.Builder()
  2.                    .conDocument(BuilderFile.READ)
  3.                    .modificarChilNode(viejoNombre, nuevoNombre)
  4.                    .build();
  5.  


Código
  1. package org.example;
  2.  
  3. import org.w3c.dom.*;
  4. import org.xml.sax.SAXException;
  5.  
  6. import javax.xml.parsers.DocumentBuilderFactory;
  7. import javax.xml.parsers.ParserConfigurationException;
  8. import javax.xml.transform.TransformerException;
  9. import javax.xml.transform.TransformerFactory;
  10. import javax.xml.transform.dom.DOMSource;
  11. import javax.xml.transform.stream.StreamResult;
  12. import java.io.File;
  13. import java.io.IOException;
  14. import java.nio.file.Path;
  15. import java.nio.file.Paths;
  16. import java.util.concurrent.atomic.AtomicBoolean;
  17. import java.util.logging.Logger;
  18. import java.util.stream.IntStream;
  19.  
  20. interface Log {
  21.    default void info(String texto) {
  22.        Logger.getLogger(Presentar.class.getSimpleName()).info(texto);
  23.    }
  24.  
  25.    default void warn(String texto) {
  26.        Logger.getLogger(Presentar.class.getSimpleName()).info(texto);
  27.    }
  28. }
  29.  
  30. enum BuilderFile {
  31.    CREATE,READ;
  32. }
  33.  
  34. /**
  35.  * @author orlando
  36.  */
  37. public class Presentar implements Log {
  38.  
  39.    private static final String PELICULA = "pelicula";
  40.    private static final String TIENDA = "tienda";
  41.  
  42.    /**
  43.      * Ruta por defecto para crear el fichero
  44.      */
  45.    private static final Path PATH_DOC_XML_FILE = Paths.get("peliculas.xml");
  46.  
  47.    /**
  48.      * Invocar primero si no existe documento
  49.      */
  50.    public void crearDocumento() {
  51.  
  52.        /**
  53.          * Instanciando Builder para crear Elemento Root e hijos
  54.          */
  55.        new Presentar.Builder()
  56.                .conDocument(BuilderFile.CREATE)
  57.                .conRootElement(TIENDA)
  58.                .conId("1")
  59.                .createNodeAndChild(PELICULA, "titulo", "Rambo 1")
  60.                .conId("2")
  61.                .createNodeAndChild(PELICULA, "titulo", "Rambo 2")
  62.                .build();
  63.  
  64.        info("Archivo creado correctamente!");
  65.  
  66.    }
  67.  
  68.  
  69.    public void presentar() {
  70.        try {
  71.  
  72.            final NodeList listaPelis = DocumentBuilderFactory.newInstance()
  73.                    .newDocumentBuilder()
  74.                    .parse(new File("peliculas.xml"))
  75.                    .getElementsByTagName(PELICULA);
  76.  
  77.            for (int i = 0; i < listaPelis.getLength(); i++) {
  78.  
  79.                Node nodo = listaPelis.item(i);
  80.  
  81.                if (nodo.getNodeType() == Node.ELEMENT_NODE) {
  82.  
  83.                    Element e = (Element) nodo;
  84.  
  85.                    NodeList hijos = e.getChildNodes();
  86.  
  87.                    for (int j = 0; j < hijos.getLength(); j++) {
  88.  
  89.                        Node hijo = hijos.item(j);
  90.  
  91.                        if (hijo.getNodeType() == Node.ELEMENT_NODE) {
  92.  
  93.                            info(hijo.getNodeName() + ":  " + hijo.getTextContent());
  94.  
  95.                        }
  96.  
  97.                    }
  98.                    info("----------------------------------------------");
  99.                }
  100.  
  101.            }
  102.  
  103.        } catch (ParserConfigurationException | SAXException | IOException ex) {
  104.            warn(ex.getMessage());
  105.        }
  106.    }
  107.  
  108.    public void Añadir() {
  109.  
  110.    }
  111.  
  112.    public void modificar(String nodoModificar, String nuevoNombre) {
  113.        try {
  114.  
  115.            new Presentar.Builder()
  116.                    .conDocument(BuilderFile.READ)
  117.                    .modificarChilNode(nodoModificar, nuevoNombre)
  118.                    .build();
  119.  
  120.        } catch (Exception e) {
  121.            warn(e.getMessage());
  122.        }
  123.    }
  124.  
  125.    public void eliminar() {
  126.  
  127.  
  128.    }
  129.  
  130.    /**
  131.      * Builder para crear elementos
  132.      */
  133.    public static class Builder implements Log {
  134.  
  135.        private Element rootElement;
  136.        private Attr attr;
  137.        private Document document;
  138.  
  139.        //Primero
  140.        public Builder conDocument(BuilderFile builderFile) {
  141.            if(builderFile == BuilderFile.CREATE) {
  142.                try {
  143.                    this.document = DocumentBuilderFactory.newInstance()
  144.                            .newDocumentBuilder()
  145.                            .newDocument();
  146.                } catch (ParserConfigurationException e) {
  147.                    warn("{} error en createNewDocument()");
  148.                }
  149.            } else if(builderFile == BuilderFile.READ){
  150.                try {
  151.                    this.document = DocumentBuilderFactory.newInstance()
  152.                            .newDocumentBuilder()
  153.                            .parse(PATH_DOC_XML_FILE.toFile());
  154.                } catch (ParserConfigurationException e) {
  155.                    warn("{} error en createNewDocument()");
  156.                } catch (SAXException e) {
  157.                    e.printStackTrace();
  158.                } catch (IOException e) {
  159.                    e.printStackTrace();
  160.                }
  161.            }
  162.  
  163.            return this;
  164.        }
  165.  
  166.        //Segundo titulo
  167.        public Builder conRootElement(final String nombre) {
  168.            this.rootElement = document.createElement(nombre);
  169.            document.appendChild(rootElement);
  170.            return this;
  171.        }
  172.  
  173.        public Builder conId(final String id) {
  174.            this.attr = document.createAttribute("id");
  175.            attr.setValue(id);
  176.            return this;
  177.        }
  178.  
  179.        //Pelicula
  180.        public Builder createNodeAndChild(final String nodeName, final String title, final String childName) {
  181.            //Node title
  182.            final Element nodeTitle = document.createElement(nodeName);
  183.            rootElement.appendChild(nodeTitle);
  184.            nodeTitle.setAttributeNode(this.attr);
  185.  
  186.            //Child title
  187.            final Element childNameTitle = document.createElement(title);
  188.            childNameTitle.appendChild(document.createTextNode(childName));
  189.            nodeTitle.appendChild(childNameTitle);
  190.            return this;
  191.        }
  192.  
  193.        public Builder modificarChilNode(final String viejoNombre, final String nuevoNombre) {
  194.            //normalizar
  195.            document.getDocumentElement().normalize();
  196.            //Lista peliculas
  197.            final NodeList listaPeliculas = document.getElementsByTagName(PELICULA);
  198.  
  199.            final AtomicBoolean value = new AtomicBoolean(true);
  200.            IntStream.range(0, listaPeliculas.getLength())
  201.                    .boxed()
  202.                    .parallel()
  203.                    .forEachOrdered(pelicula -> {
  204.                        final Node node = listaPeliculas.item(pelicula);
  205.                        if (node.getNodeType() == Node.ELEMENT_NODE) {
  206.                            final Element element = (Element) node;
  207.                            if (element.hasChildNodes()) {
  208.                                final NodeList childNodes = node.getChildNodes();
  209.                                for (int j = 0; j < childNodes.getLength(); j++) {
  210.                                    final Node child = childNodes.item(j);
  211.                                    if (child.getTextContent().equals(viejoNombre)) {
  212.                                        child.setTextContent(nuevoNombre);
  213.                                        info("Nodo: ".concat(viejoNombre)
  214.                                                .concat(" cambiado por ")
  215.                                                .concat(nuevoNombre));
  216.                                        info("Edición terminada correctamente");
  217.                                        value.set(false);
  218.                                    }
  219.                                }
  220.                            }
  221.                        }
  222.                    });
  223.            if(value.get()) {
  224.                warn("No existe el titulo");
  225.            }
  226.            return this;
  227.        }
  228.  
  229.        public Builder build() {
  230.            try {
  231.                TransformerFactory.newInstance()
  232.                        .newTransformer()
  233.                        .transform(new DOMSource(document), new StreamResult(PATH_DOC_XML_FILE.toFile()));
  234.            } catch (TransformerException e) {
  235.                warn("error al escribir en fichero .xml");
  236.            }
  237.            return this;
  238.        }
  239.    }
  240.  
  241. }
  242. }

Codigo del switch

Código
  1. //Mejor Map<String,String> a
  2.            switch (opcion) {
  3.                case 0:
  4.                    final Presentar presentar = new Presentar();
  5.                    presentar.crearDocumento();
  6.                    break;
  7.                case 1:
  8.                    Presentar p = new Presentar();
  9.                    p.presentar();
  10.                    break;
  11.                case 2:
  12.                    break;
  13.                case 3:
  14.                    entrada.nextLine();
  15.                    System.out.println("Ingresa el nodo a modificar");
  16.                    String nombreNodo = entrada.nextLine();
  17.                    System.out.println("Ingresa nuevo nombre");
  18.                    String nuevoNombre = entrada.nextLine();
  19.  
  20.                    Presentar m = new Presentar();
  21.                    m.modificar(nombreNodo, nuevoNombre);
  22.                    break;
  23.                case 4:
  24.                    break;
  25.                case 5:
  26.                    System.exit(0);
  27.                    break;
  28.                default:
  29.                    System.out.println("Opcion no valida");
  30.                    break;
  31.            }
« Última modificación: 8 Mayo 2020, 05:06 am por rub'n » En línea



rubn0x52.com KNOWLEDGE  SHOULD BE FREE.
If you don't have time to read, you don't have the time (or the tools) to write, Simple as that. Stephen ki
ryhuso

Desconectado Desconectado

Mensajes: 25


Ver Perfil
Re: modificar XML
« Respuesta #4 en: 8 Mayo 2020, 10:29 am »

Gracias  por la ayuda.
En línea

ryhuso

Desconectado Desconectado

Mensajes: 25


Ver Perfil
Re: modificar XML
« Respuesta #5 en: 8 Mayo 2020, 10:42 am »

No se si es mucha molestia... y para crear un nodo nuevo dentro de películas solo tendría que usar el builder y mandarle los datos por teclado ? y donde lo pondría al principio o al final.
En línea

rub'n


Desconectado Desconectado

Mensajes: 1.217


(e -> λ("live now")); tatuar -> λ("α");


Ver Perfil WWW
Re: modificar XML
« Respuesta #6 en: 8 Mayo 2020, 10:59 am »

No se si es mucha molestia... y para crear un nodo nuevo dentro de películas solo tendría que usar el builder y mandarle los datos por teclado ? y donde lo pondría al principio o al final.

Respuesta innesperada, pense que solo querías copiar y pegar LMAOOO

Para crear un nodo nuevo, instanciando el builder puedes hacer o añadiendo otro con el metodo añadir que te tocaría reprogramarlo, si que hay mucha informacion por ahi.

Recordemos que el Builder y su method chaining tienen cierto orden a la hora de crear Objetos entonces, sabiendo eso. puedes invocar a createNodeAndChild 3 veces, ejemplo:


Código
  1. new Presentar.Builder()
  2.            .conDocument(BuilderFile.CREATE)
  3.            .conRootElement(TIENDA)
  4.            .conId("1")
  5.            .createNodeAndChild(PELICULA, "titulo", "Rambo 1")
  6.            .conId("2")
  7.            .createNodeAndChild(PELICULA, "titulo", "Rambo 2")
  8.            .conId("3")
  9.            .createNodeAndChild(PELICULA, "titulo", "ryhuso la resurrecion")
  10.            .build();
  11.  

En línea



rubn0x52.com KNOWLEDGE  SHOULD BE FREE.
If you don't have time to read, you don't have the time (or the tools) to write, Simple as that. Stephen ki
ryhuso

Desconectado Desconectado

Mensajes: 25


Ver Perfil
Re: modificar XML
« Respuesta #7 en: 8 Mayo 2020, 11:07 am »

Básicamente lo que busco es tener un opción de añadir nueva película, si lo pongo como me dices tendría que sobrescribir el xml que ya tengo creado?
En línea

rub'n


Desconectado Desconectado

Mensajes: 1.217


(e -> λ("live now")); tatuar -> λ("α");


Ver Perfil WWW
Re: modificar XML
« Respuesta #8 en: 8 Mayo 2020, 11:09 am »

Básicamente lo que busco es tener un opción de añadir nueva película, si lo pongo como me dices tendría que sobrescribir el xml que ya tengo creado?

Tal cual dog... asi mismo.

Para añadir otro Nodo digamos, debes reprogramarlo , ya tienes una idea al menos.
En línea



rubn0x52.com KNOWLEDGE  SHOULD BE FREE.
If you don't have time to read, you don't have the time (or the tools) to write, Simple as that. Stephen ki
ryhuso

Desconectado Desconectado

Mensajes: 25


Ver Perfil
Re: modificar XML
« Respuesta #9 en: 8 Mayo 2020, 11:14 am »

bueno gracias le echare cabeza  :laugh: :laugh:
En línea

Páginas: [1] 2 Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Modificar voz
Multimedia
eLiTe 4 7,472 Último mensaje 8 Diciembre 2004, 23:13 pm
por The-skull
Modificar PDF
Programación Visual Basic
Perseus 1 2,404 Último mensaje 22 Julio 2005, 12:36 pm
por Tor
Modificar avi
Multimedia
SatDio 2 2,205 Último mensaje 11 Septiembre 2005, 22:23 pm
por ™Carlos.®
modificar un .exe
Ingeniería Inversa
alba17 6 5,305 Último mensaje 25 Octubre 2005, 22:49 pm
por raul_22
Modificar Grub para modificar propiedades de otros distros
GNU/Linux
Puntoinfinito 7 5,624 Último mensaje 2 Agosto 2012, 01:37 am
por dato000
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines