Pagina 2 di 2 primaprima 1 2
Visualizzazione dei risultati da 11 a 16 su 16
  1. #11
    non conosco Java - anche se tutto il mio team lo usa, ma per me è una fortuna! - per cui ho chiesto a ChatGPT (la richiesta di jabjoint non mi pare così sballata)

    ---------------------------------------------

    Below is one approach that uses a DOM parser and recursion to walk through every node regardless of the structure. For each node, we build a string that represents the full hierarchy (for example, "root/child/grandchild") and then extract the node’s text value. Finally, you can use JDBC (or your favorite ORM) to insert the hierarchy string and value into your database.
    Below is a sample code snippet:

    codice:
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    
    
    public class XMLParser {
    
    
        public static void main(String[] args) {
            try {
                // Parse the XML document from a file or input stream.
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = factory.newDocumentBuilder();
                Document doc = builder.parse("yourfile.xml"); // replace with your XML source
    
    
                // Normalize XML structure; it's important for parsing text nodes.
                doc.getDocumentElement().normalize();
    
    
                // Start processing from the root element.
                Element root = doc.getDocumentElement();
                traverseNode(root, root.getNodeName());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
    
        /**
         * Recursively traverse the XML nodes.
         * @param node the current node being processed
         * @param hierarchy the current path (e.g., "root/child")
         */
        private static void traverseNode(Node node, String hierarchy) {
            // Check if the node has text content that is not just whitespace.
            String value = node.getTextContent().trim();
            if (!value.isEmpty() && node.getChildNodes().getLength() == 1) {
                // Here, you could call a method to insert (hierarchy, value) into your database.
                // For example:
                // insertIntoDB(hierarchy, value);
                System.out.println("Hierarchy: " + hierarchy + " | Value: " + value);
            }
    
    
            // Process each child node recursively.
            NodeList nodeList = node.getChildNodes();
            for (int i = 0; i < nodeList.getLength(); i++) {
                Node child = nodeList.item(i);
                // Only process element nodes.
                if (child.getNodeType() == Node.ELEMENT_NODE) {
                    String childHierarchy = hierarchy + "/" + child.getNodeName();
                    traverseNode(child, childHierarchy);
                }
            }
        }
    
    
        // Example method stub for database insertion.
        /*
        private static void insertIntoDB(String hierarchy, String value) {
            // Setup JDBC connection, create a prepared statement, and execute update.
            // String sql = "INSERT INTO xml_nodes (hierarchy, node_value) VALUES (?, ?)";
        }
        */
    }

    Explanation

    1. Parsing the XML:
      The DocumentBuilderFactory and DocumentBuilder are used to parse the XML document. Once parsed, we normalize the document.

    2. Recursive Traversal:
      The traverseNode method walks through every element. It builds the hierarchy by concatenating parent node names with the current node’s name using a delimiter (here, a forward slash).

    3. Extracting Value:
      For each node, we check if its text content is not just whitespace. You might want to adjust the logic if nodes have mixed content.

    4. Database Insertion:
      The code includes a stub method insertIntoDB where you can implement your JDBC code to store the hierarchy and value into your database.

    This approach works well when you don't know the XML structure ahead of time. You can adjust the logic for handling node values or database interaction based on your specific requirements.




    -------------------------------------------------

    @jabjoint, non mi chiedere di più, che - ripeto - Java non lo conosco!

  2. #12
    Quote Originariamente inviata da optime Visualizza il messaggio
    non conosco Java - anche se tutto il mio team lo usa, ma per me è una fortuna! - per cui ho chiesto a ChatGPT (la richiesta di jabjoint non mi pare così sballata)

    ---------------------------------------------

    Below is one approach that uses a DOM parser and recursion to walk through every node regardless of the structure. For each node, we build a string that represents the full hierarchy (for example, "root/child/grandchild") and then extract the node’s text value. Finally, you can use JDBC (or your favorite ORM) to insert the hierarchy string and value into your database.
    Below is a sample code snippet:

    codice:
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    
    
    public class XMLParser {
    
    
        public static void main(String[] args) {
            try {
                // Parse the XML document from a file or input stream.
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = factory.newDocumentBuilder();
                Document doc = builder.parse("yourfile.xml"); // replace with your XML source
    
    
                // Normalize XML structure; it's important for parsing text nodes.
                doc.getDocumentElement().normalize();
    
    
                // Start processing from the root element.
                Element root = doc.getDocumentElement();
                traverseNode(root, root.getNodeName());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
    
        /**
         * Recursively traverse the XML nodes.
         * @param node the current node being processed
         * @param hierarchy the current path (e.g., "root/child")
         */
        private static void traverseNode(Node node, String hierarchy) {
            // Check if the node has text content that is not just whitespace.
            String value = node.getTextContent().trim();
            if (!value.isEmpty() && node.getChildNodes().getLength() == 1) {
                // Here, you could call a method to insert (hierarchy, value) into your database.
                // For example:
                // insertIntoDB(hierarchy, value);
                System.out.println("Hierarchy: " + hierarchy + " | Value: " + value);
            }
    
    
            // Process each child node recursively.
            NodeList nodeList = node.getChildNodes();
            for (int i = 0; i < nodeList.getLength(); i++) {
                Node child = nodeList.item(i);
                // Only process element nodes.
                if (child.getNodeType() == Node.ELEMENT_NODE) {
                    String childHierarchy = hierarchy + "/" + child.getNodeName();
                    traverseNode(child, childHierarchy);
                }
            }
        }
    
    
        // Example method stub for database insertion.
        /*
        private static void insertIntoDB(String hierarchy, String value) {
            // Setup JDBC connection, create a prepared statement, and execute update.
            // String sql = "INSERT INTO xml_nodes (hierarchy, node_value) VALUES (?, ?)";
        }
        */
    }

    Explanation

    1. Parsing the XML:
      The DocumentBuilderFactory and DocumentBuilder are used to parse the XML document. Once parsed, we normalize the document.

    2. Recursive Traversal:
      The traverseNode method walks through every element. It builds the hierarchy by concatenating parent node names with the current node’s name using a delimiter (here, a forward slash).

    3. Extracting Value:
      For each node, we check if its text content is not just whitespace. You might want to adjust the logic if nodes have mixed content.

    4. Database Insertion:
      The code includes a stub method insertIntoDB where you can implement your JDBC code to store the hierarchy and value into your database.

    This approach works well when you don't know the XML structure ahead of time. You can adjust the logic for handling node values or database interaction based on your specific requirements.




    -------------------------------------------------

    @jabjoint, non mi chiedere di più, che - ripeto - Java non lo conosco!

    Grazie è quello che chiedevo e in rete deserto.
    Nel 2025 oramai c'è ChatGPT che ci sostituirà tutti.
    jabjoint

  3. #13
    prego! ma toglimi una curiosità: stai costruendo un parser generico per trattare XML di cui non conosci origine, struttura, ecc ecc, o devi trattare questo XML in un applicativo? Strano che tu non ne conosca la struttura...

  4. #14
    Quote Originariamente inviata da optime Visualizza il messaggio
    prego! ma toglimi una curiosità: stai costruendo un parser generico per trattare XML di cui non conosci origine, struttura, ecc ecc, o devi trattare questo XML in un applicativo? Strano che tu non ne conosca la struttura...
    Si conosco la struttura.
    Ti tolgo la curiosità come gentilmente chiedi:

    Si tratterebbe di accedere ai TAG XML strutturati per la creazione di una SWING-JAVA.
    Tuttavia preferisco sempre estendere-generalizzare il compito dell'algoritmo perché spesso occorre ed è più conveniente.
    jabjoint

  5. #15
    Ero non tanto interessato comunque a come eseguire con Java il compito, ero maggiormente interessato invece a come viene implementato da un algoritmo in modo efficiente.
    Mi interessa il procedimento logico, meglio espresso discorsivamente.
    jabjoint

  6. #16
    Quote Originariamente inviata da alka Visualizza il messaggio
    Mi sembra un sistema alquanto inefficiente, soprattutto avendo a disposizione linguaggi (e relative strutture in memoria) di alto livello, visto che continui a scandire e rileggere comunque nodi che hai già elaborato, per caricarli oppure per saltarli.

    In aggiunta, è inutilmente farraginoso: non esiste una motivazione per cui uno dovrebbe fare una cosa del genere, potendosi caricare in memoria i dati in una struttura gerarchica.


    Non si capiscono i motivi per cui si dovrebbe fare una simile navigazione nel file, navigando quello che è un albero ripetute volte.

    Per la lettura del file senza determinare a priori il nome dei tag e leggendolo progressivamente, è già prevista la modalità SAX.

    In sintesi, qualunque cosa tu voglia fare con XML, esiste già una implementazione: se non esiste quella che vuoi fare tu, significa che quello che vuoi fare è meno efficiente o utile di quanto non sia già reso disponibile.


    Forse era meglio postare nel forum di Java, visto che si parla di questo linguaggio e non specificatamente di un problema col formato XML in sé, quanto più di modi per leggero scrivendo codice (in Java, in questo caso).
    Può darsi che potrebbe discorsivamente spiegare come potrei fare.
    jabjoint

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.