Pagina 1 di 4 1 2 3 ... ultimoultimo
Visualizzazione dei risultati da 1 a 10 su 33
  1. #1

    Come prendere in java tutti i figli di un nodo?

    Come faccio a scrivere un merodo che passato in ingresso un Nodo e una String mi trovi, nel nodo padre tutti i nodi figlio con quel nome?


    Io ho questo metodo in cui il chiamante passa un oggetto Node al cui interno cercare un Nodo "figlio" il cui nome corrisponda a quello cercato, cioè il parametro "nodeName".

    Il Nodo passato come parametro potrebbe contenere zero o più Nodi "figli"...
    la lista di tutti i "nodi figli" contenuti in un dato nodo viene ottenuta così:

    codice:
    NodeList childNodes = node.getChildNodes();Ora in "childNodes" c'è la lista di tutti i nodi figlio di "node".
    Però il resto del metodo si limita a prendere un "nodo figlio" dalla lista, controllare se il suo nome è uguale a quello voluto ("nodeName"), quindi tornare quel Nodo in caso affermativo, altrimenti proseguire l'iterazione prendendo il prossimo "nodo figlio" e così via, finchè non l'ha trovato o non ha raggiunto la fine della lista.
    Chiaro che appena trova il primo che corrisponde, il metodo torna subito.

    codice:
      private Node getChildNode(Node node, String nodeName) {
        NodeList childNodes = node.getChildNodes();
        for ( int i = 0; i < childNodes.getLength(); i++) {
          Node childNode = childNodes.item(i);
        if ( childNode.getNodeName().equals(nodeName) )
            return childNode;
        }
        return null;
      }
    Invece io devo fare che il metodo ritornino tutti i figli con quel "nodeName" e non solo il primo che incontra...avete un idea di come possa fare?

  2. #2
    Utente di HTML.it L'avatar di andbin
    Registrato dal
    Jan 2006
    residenza
    Italy
    Messaggi
    18,284

    Re: Come prendere in java tutti i figli di un nodo?

    Originariamente inviato da xxdavide84xx
    Invece io devo fare che il metodo ritornino tutti i figli con quel "nodeName" e non solo il primo che incontra...avete un idea di come possa fare?
    Dipende cosa vuoi far ritornare dal metodo! Node ovviamente no, visto che rappresenta solo 1 nodo. Potresti far ritornare un List<Node> (nel metodo crei ad esempio un ArrayList e ci appendi tutti i nodi che devi far ritornare).

    Ma potresti anche far ritornare un NodeList. Nota che NodeList non è una classe ma una interfaccia. Quindi devi far ritornare una implementazione "concreta" di questa interfaccia. Quale implementazione? Semplice, la definisci tu! NodeList è molto semplice, ha solo 2 metodi: getLength() e item() e questi dati (lunghezza e elemento i-esimo) li hai anche da un ArrayList.

    Se non ti è chiaro, specialmente il ritorno di un NodeList, dimmelo che posso fare un esempio.
    Andrea, andbin.devSenior Java developerSCJP 5 (91%) • SCWCD 5 (94%)
    java.util.function Interfaces Cheat SheetJava Versions Cheat Sheet

  3. #3
    Gli esempi sono sempre ben accetti....
    Cmq guardando queste pagine mi sembra di avere trovato come si comporta i Nodi..
    XML di Steve Holzner (pag 480,481,482)

    Il mio codice completo è questo:
    codice:
    import java.io.*;
    import java.util.*;
    import javax.xml.parsers.*;
    import org.w3c.dom.*;
    
    public class aa  {
      Vector styleNodes = new Vector();
    
      Vector styleObjects = new Vector();
    
      Vector rNodes = new Vector();
    
      Vector bodyNodes = new Vector();
    
      Vector bodyObjects = new Vector();
    
      public aa() {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = null;
        try {
          builder = factory.newDocumentBuilder();
        }
        catch (ParserConfigurationException e) {
          e.printStackTrace();
          System.exit(1);
        }
        Document document = null;
        try {
          PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("Martedì 15.txt", false)));
          document = builder.parse(new File("C:\\Documents and settings\\Administrator\\Desktop\\DAVIDE\\Dom\\tesi.xml"));
          findStyleNodes(document);
          createStyleObjects();
          printStyles(pw);
          findBodyNodes(document);
          createBodyObjects();
          printBody(pw);
          pw.close();
        }
        catch (Exception e) {
          e.printStackTrace();
          System.exit(1);
        }
      }
    
      private void findStyleNodes(Node startingNode) {
        NodeList childNodes = startingNode.getChildNodes();
        for ( int i = 0; i < childNodes.getLength(); i++) {
          Node actualNode = childNodes.item(i);
          if ( isStyleNode(actualNode) )
            styleNodes.addElement(actualNode);
          if ( actualNode.hasChildNodes() )
            findStyleNodes(actualNode);
        }
      }
    
      private boolean isStyleNode(Node node) {
        return node.getNodeName().equals("w:style");
      }
    
      private void createStyleObjects() {
        for ( int i = 0; i < styleNodes.size(); i++) {
          Node styleNode = (Node)styleNodes.elementAt(i);
          Style style = new Style();
          Node uinameNode = getChildNode(styleNode, "wx:uiName");
          if ( uinameNode != null )
            style.name = getAttributeValue(uinameNode, "wx:val");
          if ( uinameNode == null ) {
            Node nameNode = getChildNode(styleNode, "w:name");
            if ( nameNode != null )
              style.name = getAttributeValue(nameNode, "w:val");
          }
          Node basedNode = getChildNode(styleNode, "w:basedOn");
          if ( basedNode != null )
            style.based = getAttributeValue(basedNode, "w:val");
          Node pPrNode = getChildNode(styleNode, "w:pPr");
          if ( pPrNode != null ) {
            Node pstileNode = getChildNode(pPrNode, "w:pStyle");
            if ( pstileNode != null )
              style.pstile = getAttributeValue(pstileNode, "w:val");
            Node jcNode = getChildNode(pPrNode, "w:jc");
            if ( jcNode != null )
              style.jc = getAttributeValue(jcNode, "w:val");
          }
          Node paragraphNode = getChildNode(styleNode, "w:rPr");
          if ( paragraphNode != null ) {
            Node fontNode = getChildNode(paragraphNode, "wx:font");
            if ( fontNode != null )
              style.font = getAttributeValue(fontNode, "wx:val");
            Node sizeNode = getChildNode(paragraphNode, "w:sz");
            if ( sizeNode != null )
              style.size = getAttributeValue(sizeNode, "w:val");
            Node grassettoNode = getChildNode(paragraphNode, "w:b");
            if ( grassettoNode != null )
              style.grassetto = getAttributeValue(grassettoNode, "w:val");
            Node italicoNode = getChildNode(paragraphNode, "w:i");
            if ( italicoNode != null )
              style.italico = getAttributeValue(italicoNode, "w:val");
            Node sottolineatoNode = getChildNode(paragraphNode, "w:u");
            if ( sottolineatoNode != null )
              style.sottolineato = getAttributeValue(sottolineatoNode, "w:val");
          }
          styleObjects.addElement(style);
        }
      }
    
      private String getAttributeValue(Node node, String attributeName) {
        NamedNodeMap attributes = node.getAttributes();
        if ( attributes == null )
          return "";
        Node item = attributes.getNamedItem(attributeName);
        if ( item == null )
          return "";
        return item.getNodeValue();
      }
    
      private Node getChildNode(Node node, String nodeName) {
        NodeList childNodes = node.getChildNodes();
        for ( int i = 0; i < childNodes.getLength(); i++) {
          Node childNode = childNodes.item(i);
          
        if ( childNode.getNodeName().equals(nodeName) )      
            return childNode;
        }
        
        return null;
      }
    
      private void printStyles(PrintWriter pw) {
        for ( int i = 0; i < styleObjects.size(); i++) {
          Style style = (Style)styleObjects.elementAt(i);
          System.out.println(style);
          pw.println(style);
        }
      }
    
      public static void main(String args[]) {
        new aa();
      }
    
      class Style  {
        String name;
    
        String based;
    
        String pstile;
    
        String jc;
    
        String font;
    
        String size;
    
        String grassetto;
    
        String italico;
    
        String sottolineato;
    
        public String toString() {
          StringBuffer buffer = new StringBuffer();
          if ( name != null ) {
            buffer.append("Stile: " + name + "\n");
            if ( based != null )
              buffer.append(" Basato su: " + based + "\n");
            if ( pstile != null )
              buffer.append(" pStyle: " + pstile + "\n");
            if ( jc != null )
              buffer.append(" Jc: " + jc + "\n");
            if ( font != null )
              buffer.append(" Font: " + font + "\n");
            if ( size != null )
              buffer.append(" Dimensione: " + size + "\n");
            if ( grassetto != null )
              buffer.append(" Grassetto " + grassetto + "\n");
            if ( italico != null )
              buffer.append(" Italico " + italico + "\n");
            if ( sottolineato != null )
              buffer.append(" Sottolineato: " + sottolineato + "\n");
          }
          return buffer.toString();
        }
      }
    
      private void findBodyNodes(Node startingNode) {
        NodeList childNodes = startingNode.getChildNodes();
        for ( int i = 0; i < childNodes.getLength(); i++) {
          Node actualNode = childNodes.item(i);
          if ( isBodyNode(actualNode) )
            bodyNodes.addElement(actualNode);
          if ( actualNode.hasChildNodes() )
            findBodyNodes(actualNode);
        }
      }
    
      private boolean isBodyNode(Node node) {
        return node.getNodeName().equals("w:p");
      }
    
      private void createBodyObjects() {
        for ( int i = 0; i < bodyNodes.size(); i++) {
          Node bodyNode = (Node)bodyNodes.elementAt(i);
          Body body = new Body();
          Node paragraphNode = getChildNode(bodyNode, "w:pPr");
          if ( paragraphNode != null ) {
            Node stileNode = getChildNode(paragraphNode, "w:pStyle");
            if ( stileNode != null )
              body.stile = getAttributeValue(stileNode, "w:val");
            Node jcNode = getChildNode(paragraphNode, "w:jc");
            if ( jcNode != null )
              body.jc = getAttributeValue(jcNode, "w:val");
          }
          createRObjects(body, bodyNode);
          bodyObjects.addElement(body);
        }
      }
    
      private void createRObjects(Body body, Node bodyNode) {
        Node rNode = getChildNode(bodyNode, "w:r");
        if ( rNode != null ) {
          Node rPrNode = getChildNode(rNode, "w:rPr");
          if ( rPrNode != null ) {
            Node grassettoNode = getChildNode(rPrNode, "w:b");
            if ( grassettoNode != null )
              body.grassetto = getAttributeValue(grassettoNode, "w:val");
            Node italicoNode = getChildNode(rPrNode, "w:i");
            if ( italicoNode != null )
              body.italico = getAttributeValue(italicoNode, "w:val");
          }
          Node testoNode = getChildNode(rNode, "w:t");
          if ( testoNode != null ) {
            Node testoNode1 = getChildNode(testoNode, "#text");
            if ( testoNode1 != null )
              body.testo = testoNode1.getNodeValue();
          }
        }
      }
    
      private void printBody(PrintWriter pw) {
        for ( int i = 0; i < bodyObjects.size(); i++) {
          Body body = (Body)bodyObjects.elementAt(i);
          System.out.println(body);
          pw.println(body);
        }
      }
    
      class Body  {
        String stile;
    
        String jc;
    
        String grassetto;
    
        String italico;
    
        String testo;
    
        public String toString() {
          StringBuffer buffer = new StringBuffer();
          if ( stile != null )
            buffer.append("Stile body: " + stile + "\n");
          if ( jc != null )
            if ( grassetto != null )
              buffer.append(" Grassetto body " + grassetto + "\n");
          if ( italico != null )
            buffer.append(" Italico body " + italico + "\n");
          buffer.append(" Testo body: " + testo + "\n");
          return buffer.toString();
        }
      }
    }
    il problema riguarda private void createRObjects(Body body, Node bodyNode)
    visto che mi stampa solo il primo w:r contenuto in w:p....invece mi dovrebbe stampare tutti i w:r contenuti in w:p....

  4. #4
    Utente di HTML.it L'avatar di andbin
    Registrato dal
    Jan 2006
    residenza
    Italy
    Messaggi
    18,284
    Originariamente inviato da xxdavide84xx
    il problema riguarda private void createRObjects(Body body, Node bodyNode)
    visto che mi stampa solo il primo w:r contenuto in w....invece mi dovrebbe stampare tutti i w:r contenuti in w....
    Non ho letto tutto il tuo codice chilometrico ma mi sembra abbastanza ovvio. Per come hai definito/implementato getChildNode, fa ritornare il primo Node che trova con quel nome e basta. Se vuoi far ritornare più nodi, devi ovviamente cambiare il tipo di ritorno del metodo (e qui torniamo alla mia domanda precedente: che tipo vuoi far ritornare?) e cambiare la implementazione.
    Andrea, andbin.devSenior Java developerSCJP 5 (91%) • SCWCD 5 (94%)
    java.util.function Interfaces Cheat SheetJava Versions Cheat Sheet

  5. #5
    Tu cosa mi consigli?
    Io pensavo di lasciare quel metodo...
    e poi di impostarne un'altro per w:r

    w:p è così composto:

    quindi dentro w:p ci sarà sempre 1 ed 1 solo w:pPr
    mentre ci possono essere 0 o più w:r.....

    Io devo cambiare il pezzo per fare comparerire tutti i w:r e non solo il primo....detto questo chiedo a te consigli su che soluzione adottare....
    Cmq sarei interessato agli esempi che mi avevi proposto prima!

    Quindi in w:p getChildNode va bene...per raccogliere w:pPr....
    devo cambiare la parte in cui prendo i w:r....che ne devo raccogliere più di 1....

    Cmq ho notato che
    codice:
    private Node getChildNode(Node node, String nodeName) {
        NodeList childNodes = node.getChildNodes();
        for ( int i = 0; i < childNodes.getLength(); i++) {
          Node childNode = childNodes.item(i);
          if ( childNode.getNodeName().equals(nodeName) )
            return childNode;
        }
        return null;
      }
    che in getChildNode
    ho già NodeList....
    quindi è solo SBAGLIATO il return??? e forse anche l'if...

  6. #6
    Utente di HTML.it L'avatar di andbin
    Registrato dal
    Jan 2006
    residenza
    Italy
    Messaggi
    18,284
    Fai una semplice classe che implementa NodeList:

    codice:
    class ArrayNodeList implements NodeList
    {
        private ArrayList<Node> nodesArray = new ArrayList<Node> ();
    
        public void add (Node n)
        {
            nodesArray.add (n);
        }
    
        public int getLength ()
        {
            return nodesArray.size ();
        }
    
        public Node item (int index)
        {
            try {
                return nodesArray.get (index);
            } catch (IndexOutOfBoundsException e) {
                return null;
            }
        }
    }
    Poi fai un metodo getChildNodes:

    codice:
    public NodeList getChildNodes (Node node, String name)
    {
        ArrayNodeList arrNodeList = new ArrayNodeList ();
    
        NodeList nodeList = node.getChildNodes ();
    
        for (int i = 0; i < nodeList.getLength (); i++)
        {
            Node childNode = nodeList.item (i);
    
            if (childNode.getNodeType () == org.w3c.dom.Node.ELEMENT_NODE &&
                childNode.getNodeName ().equals (name))
            {
                arrNodeList.add (childNode);
            }
        }
    
        return arrNodeList;
    }
    Andrea, andbin.devSenior Java developerSCJP 5 (91%) • SCWCD 5 (94%)
    java.util.function Interfaces Cheat SheetJava Versions Cheat Sheet

  7. #7
    getChildNodes esiste già negli array. non sarebbe meglio chiamarlo in un altro MODO??
    esattamente
    NodeList getChildNodes ()
    restituisce una NodeList contenente tutti i figli del nodo corrente.....

    Ed io in qualche caso la uso nel mio programma!!!

    forse sarebbe meglio chiamarla
    getAllChildNode
    che ne dici?

    Inoltre ho visto che esegui quel
    private ArrayList <Node> nodesArray = new ArrayList<Node> ();
    di Java 5....

    Se io volessi fare senza <Node> dove dovrei fare il cast???

  8. #8
    Utente di HTML.it L'avatar di andbin
    Registrato dal
    Jan 2006
    residenza
    Italy
    Messaggi
    18,284
    Originariamente inviato da xxdavide84xx
    getChildNodes esiste già negli array. non sarebbe meglio chiamarlo in un altro MODO??
    esattamente
    NodeList getChildNodes ()
    restituisce una NodeList contenente tutti i figli del nodo corrente.....
    Se ti riferisci al getChildNodes() della classe Node, è chiaro che lo invochi su un Node e quindi non c'è ambiguità o conflitto.

    Originariamente inviato da xxdavide84xx
    forse sarebbe meglio chiamarla
    getAllChildNode
    che ne dici?
    getChildNodesByName. Ma poi ovviamente chiamalo come ti pare. Io ho solo fatto un esempio.
    Andrea, andbin.devSenior Java developerSCJP 5 (91%) • SCWCD 5 (94%)
    java.util.function Interfaces Cheat SheetJava Versions Cheat Sheet

  9. #9
    Per fare il cast come dovrei fare?

  10. #10
    Utente di HTML.it L'avatar di andbin
    Registrato dal
    Jan 2006
    residenza
    Italy
    Messaggi
    18,284
    Originariamente inviato da xxdavide84xx
    Per fare il cast come dovrei fare?
    Di quale cast parli??
    Andrea, andbin.devSenior Java developerSCJP 5 (91%) • SCWCD 5 (94%)
    java.util.function Interfaces Cheat SheetJava Versions Cheat Sheet

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.