Pagina 2 di 2 primaprima 1 2
Visualizzazione dei risultati da 11 a 13 su 13
  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...

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.