This discussion is archived
8 Replies Latest reply: Apr 1, 2013 9:20 AM by biochemistry43 RSS

XML data in TableView

biochemistry43 Newbie
Currently Being Moderated
Hi all:

I would like to populate a TableView with data from an XML file but I can not.

Shortly JavaFX understand and appreciate any help.

DataFX I tried but did not get it.

thanks

Note: My table is created with FXML
  • 1. Re: XML data in TableView
    993317 Newbie
    Currently Being Moderated
    Hi,
    First you will need to extract the data from the XML into some pojo/bean, then use this to pouplate the TableView. You will find many resources on creating a TableView and TableColumns.
    You can go through this http://docs.oracle.com/javafx/2/ui_controls/table-view.htm
    and http://docs.oracle.com/javafx/2/api/javafx/scene/control/TableView.html

    Edited by: 990314 on Mar 11, 2013 10:33 PM
  • 2. Re: XML data in TableView
    James_D Guru
    Currently Being Moderated
    Parse the XML in the controller. I don't work with XML, so there may be easier ways to do it than this that I'm not aware of, but using the basic API you can do:

    XMLTableExampleController.java
    import java.io.FileReader;
    import java.util.ArrayList;
    import java.util.List;
    
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.stream.XMLStreamException;
    
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import org.xml.sax.InputSource;
    
    import javafx.beans.property.SimpleStringProperty;
    import javafx.beans.property.StringProperty;
    import javafx.fxml.FXML;
    import javafx.scene.control.TableView;
    
    
    public class XMLTableExampleController {
      
      @FXML private TableView<Person> table ;
      
      private static final String XML_FILE_NAME = "PersonList.xml" ;
    
      public void initialize() throws Exception {
        table.getItems().addAll(readXMLData());
      }
      
      private List<Person> readXMLData() throws Exception {
        DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document xmlDoc = docBuilder.parse(new InputSource(new FileReader(XML_FILE_NAME)));
        Element root = xmlDoc.getDocumentElement() ;
        if (! root.getTagName().equals("PersonList")) {
          throw new XMLStreamException("Root element must be PersonList");
        }
        List<Person> people = new ArrayList<Person>();
        
        NodeList personNodeList = root.getElementsByTagName("Person") ;
        int numPeople = personNodeList.getLength();
        for (int i=0; i<numPeople; i++) {
          Node personNode = personNodeList.item(i);
          String firstName = "" ;
          String lastName = "" ;
          NodeList personChildNodes = personNode.getChildNodes();
          for (int j=0; j<personChildNodes.getLength(); j++) {
            Node childNode = personChildNodes.item(j);
            if (childNode.getNodeName().equals("FirstName")) {
              firstName = childNode.getTextContent();
            } else if (childNode.getNodeName().equals("LastName")) {
              lastName = childNode.getTextContent();
            }
          }
          people.add(new Person(firstName, lastName));
        }
        
        
        return people ;
      }
      
      public class Person {
        private final StringProperty firstName ;
        private final StringProperty lastName ;
        Person(String firstName, String lastName) {
          this.firstName = new SimpleStringProperty(this, "firstName", firstName);
          this.lastName = new SimpleStringProperty(this, "lastName", lastName);
        }
        public String getFirstName() { return firstName.get(); }
        public void setFirstName(String firstName) { this.firstName.set(firstName);}
        public StringProperty firstNameProperty() { return firstName ; }
        public String getLastName() { return lastName.get(); }
        public void setLastName(String lastName) { this.lastName.set(lastName); }
        public StringProperty lastNameProperty() { return lastName ; }
      }
    
    }
    which loads the following example file

    PersonList.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <PersonList>
         <Person>
              <FirstName>Hugo</FirstName>
              <LastName>Lloris</LastName>
         </Person>
         <Person>
              <FirstName>Benoit</FirstName>
              <LastName>Assou-Ekotto</LastName>
         </Person>
         <Person>
              <FirstName>Michael</FirstName>
              <LastName>Dawson</LastName>
         </Person>
         <Person>
              <FirstName>Jan</FirstName>
              <LastName>Vertonghen</LastName>
         </Person>
         <Person>
              <FirstName>Kyle</FirstName>
              <LastName>Walker</LastName>
         </Person>
         <Person>
              <FirstName>Moussa</FirstName>
              <LastName>Dembele</LastName>
         </Person>
         <Person>
              <FirstName>Scott</FirstName>
              <LastName>Parker</LastName>
         </Person>
         <Person>
              <FirstName>Gylfi</FirstName>
              <LastName>Sigurdsson</LastName>
         </Person>
         <Person>
              <FirstName>Gareth</FirstName>
              <LastName>Bale</LastName>
         </Person>
         <Person>
              <FirstName>Aaron</FirstName>
              <LastName>Lennon</LastName>
         </Person>
         <Person>
              <FirstName>Jermaine</FirstName>
              <LastName>Defoe</LastName>
         </Person>
    </PersonList>
    XMLTableExample.fxml
    <?xml version="1.0" encoding="UTF-8"?>
    
    <?import javafx.scene.layout.BorderPane?>
    <?import javafx.scene.control.TableView?>
    <?import javafx.scene.control.TableColumn?>
    <?import javafx.scene.control.cell.PropertyValueFactory?>
    
    <BorderPane xmlns:fx="http://javafx.com/fxml" fx:controller="XMLTableExampleController">
         <center>
              <TableView fx:id="table">
                   <columns>
                        <TableColumn text="First Name">
                             <cellValueFactory>
                                  <PropertyValueFactory property="firstName" />
                             </cellValueFactory>
                        </TableColumn>
                        <TableColumn text="Last Name">
                             <cellValueFactory>
                                  <PropertyValueFactory property="lastName" />
                             </cellValueFactory>
                        </TableColumn>
                   </columns>
              </TableView>
         </center>
    </BorderPane>
    XMLTableExample.java
    import java.io.IOException;
    
    import javafx.application.Application;
    import javafx.fxml.FXMLLoader;
    import javafx.scene.Parent;
    import javafx.scene.Scene;
    import javafx.stage.Stage;
    
    public class XMLTableExample extends Application {
    
         @Override
         public void start(Stage primaryStage) throws IOException {
              Parent root = FXMLLoader.load(getClass().getResource("XMLTableExample.fxml"));
              Scene scene = new Scene(root, 300, 400);
              primaryStage.setScene(scene);
              primaryStage.show();
         }
    
         public static void main(String[] args) {
              launch(args);
         }
    }
  • 3. Re: XML data in TableView
    biochemistry43 Newbie
    Currently Being Moderated
    look ... This is the file you need to read the data "name", "id", "color" and "W" found inside the tag "line" within "lines" in "Figures", within "Tactical_Graphics ".

    This something nested and this having a bit of difficulty with that.

    Besides, I need to somehow save the data that is on the label "coordinates" on some object or something.
    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <xml>
       <Military_Scenario>
                <Overlags/>
              <Instalations/>
              <Tactical_Graphics>
                   <DerrotasPatrones/>
                   <Figuras>
                        <lineas>
                             <linea>
                                  <Nombre>punto1</Nombre>
                                  <id>1</id>
                                  <color>negro</color>
                                  <ancho>3</ancho>
                                  <coordenadas>
                                       <coordenada>
                                            <latitud>123456</latitud>
                                            <longitud>2546</longitud>
                                       </coordenada>
                                       <coordenada>
                                            <latitud>145656</latitud>
                                            <longitud>22246</longitud>
                                       </coordenada>
                                       <coordenada>
                                            <latitud>12345686</latitud>
                                            <longitud>21256</longitud>
                                       </coordenada>
                                       <coordenada>
                                            <latitud>1212356</latitud>
                                            <longitud>212656</longitud>
                                       </coordenada>
                                       <coordenada>
                                            <latitud>12344562</latitud>
                                            <longitud>212355</longitud>
                                       </coordenada>
                                       <coordenada>
                                            <latitud>1232354</latitud>
                                            <longitud>2253566</longitud>
                                       </coordenada>
                                       <coordenada>
                                            <latitud>1226326</latitud>
                                            <longitud>2223156</longitud>
                                       </coordenada>
                                  </coordenadas>
                             </linea>
                        </lineas>
                   </Figuras>
              </Tactical_Graphics>
              <MOOTWGrapchics/>
         </Military_Scenario>
    </xml>
  • 4. Re: XML data in TableView
    James_D Guru
    Currently Being Moderated
    Your code should be very similar to the code I showed in the example. If you want, you could check the structure of the xml file; but if you're only interested in the lines and coordinates inside them you can just grab all the "linea" tags from the document:

    - Get the document
    - Create an empty list of Lines
    - Get the elements in the document which correspond to lines with document.getElementsByTagName("linea"). This returns a NodeList object
    - For each "line" element
    - - Get the child nodes of the line element, iterate through them, and figure the data for the line
    - - For the "coordenada" child, create an empty list of coordinates, get the child nodes of the coordenada node, and iterate through them to populate the list
    - - Use the data to create the line object
    - - add the line object to the list of lines
  • 5. Re: XML data in TableView
    biochemistry43 Newbie
    Currently Being Moderated
    I tried to read it more nested us:

    but I get an error:

    java.lang.NullPointerException

    in this line:
     NodeList elementosTacticos = tacticalGraphics.getChildNodes();
    private List<CoordenadasLinea> leeCoordLineaDesdeXML() throws ParserConfigurationException, FileNotFoundException, SAXException, IOException, XMLStreamException 
        {
            DocumentBuilder docBuilder =DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document XMLDoc = docBuilder.parse(new InputSource(new FileReader("C:/Users/Administrador/Documents/NetBeansProjects/Signa/Estructura.xml")));
            System.out.println("El Documento es: " + XMLDoc.toString());
            Element root = XMLDoc.getDocumentElement();
            if (! root.getTagName().equals("xml")) {
            throw new XMLStreamException("El elemento principal debe ser \"xml\" ");
            }
            List<CoordenadasLinea> coodLineas = new ArrayList<CoordenadasLinea>();
            
            Node militaryScenario = root.getFirstChild();
            NodeList elementos = militaryScenario.getChildNodes();
            Node tacticalGraphics = elementos.item(7);
            NodeList elementosTacticos = tacticalGraphics.getChildNodes();
            Node figuras = elementosTacticos.item(1);
            NodeList listaFiguras = figuras.getChildNodes();
            Node lineas = listaFiguras.item(0);
            NodeList listaLineas = lineas.getChildNodes();
            int numDeLineas = listaLineas.getLength();
            for (int i = 0; i < numDeLineas; i++)
            {
                Node linea = listaLineas.item(i);
                NodeList atribsLinea = linea.getChildNodes();
                for (int j = 0; j < atribsLinea.getLength(); j++)
                {
                    int id = 0;
                    String latitud = "";
                    String longitud = "";
                    Node atribLinea = atribsLinea.item(j);
                    if (atribLinea.getNodeName().equals("coordenadas")) {
                        NodeList coordenadas = atribLinea.getChildNodes();
                        for (int k = 0; k < coordenadas.getLength(); k++)
                        {
                            Node coordenada = coordenadas.item(k);
                            if (coordenada.getNodeName().equals("latitud"))
                            {
                                latitud = coordenada.getTextContent();
                            }
                            else if (coordenada.getNodeName().equals("latitud"))
                            {
                                longitud = coordenada.getTextContent();
                            }
                            else if (coordenada.getNodeName().equals("item"))
                            {
                                id = Integer.parseInt(coordenada.getTextContent());
                            }
                        }
                    }
                    coodLineas.add(new CoordenadasLinea(id, latitud, longitud));
                }
            }
            return coodLineas;
        }
    I experimented and this line is null:
    Document XMLDoc = docBuilder.parse(new InputSource(new FileReader("C:/Users/Administrador/Documents/NetBeansProjects/Signa/Estructura.xml")));
            System.out.println("El Documento es: " + XMLDoc.toString());
    El Documento es: [#document: null]
  • 6. Re: XML data in TableView
    James_D Guru
    Currently Being Moderated
    biochemistry43 wrote:
    I tried to read it more nested us:

    but I get an error:

    java.lang.NullPointerException

    in this line:
    NodeList elementosTacticos = tacticalGraphics.getChildNodes();
    So that means tacticalGraphics is null...
    Node militaryScenario = root.getFirstChild();
    NodeList elementos = militaryScenario.getChildNodes();
    Node tacticalGraphics = elementos.item(7);
    NodeList elementosTacticos = tacticalGraphics.getChildNodes();
    which makes sense since (at least in the example you posted) the militaryScenario element only had 4 child nodes. In that example, tacticalGraphics would be elementos.item(2).
    I experimented and this line is null:
    Document XMLDoc = docBuilder.parse(new InputSource(new FileReader("C:/Users/Administrador/Documents/NetBeansProjects/Signa/Estructura.xml")));
    System.out.println("El Documento es: " + XMLDoc.toString());
    El Documento es: [#document: null]
    XMLDoc is not null, else you would get a null pointer exception when you called XMLDoc.getDocumentElement(). I'm not sure what the toString() method of the Document implementation gives you.

    There are a ton of references online for parsing XML in Java. [url http://www.mkyong.com/java/how-to-read-xml-file-in-java-dom-parser/]Here is one just by a quick random google search that probably has enough for you to do what you need. [url http://docs.oracle.com/javase/6/docs/jre/api/plugin/dom/]Here are the Javadocs for the XML API.
  • 7. Re: XML data in TableView
    biochemistry43 Newbie
    Currently Being Moderated
    ok James ... thank you very much.

    You've been very helpful this week.

    God bless you
  • 8. Re: XML data in TableView
    biochemistry43 Newbie
    Currently Being Moderated
    I leave here what finally did. Perhaps it serves the mostly Spanish speakers.

    I found a library for parsing XML. The library is in Spanish and is called JespXML. It is very convenient and easy to use.

    To populate a table with data from XML ... This I did.
    public void readLinesFromXML(String xmlFile)
        {
            //JespXML library. With this single statement read XML file
            JespXML archivoPlanSigna = new JespXML(xmlFile);
    
            try {
                //leerXML method reads the root tag and saves it to an object Tag    
                Tag xml = archivoPlanSigna.leerXML();
                
                List<CoordenadasLinea> coodLineas = new ArrayList<CoordenadasLinea>();
    
                            
                Tag tagMilitaryScenario = xml.getTagHijoByName("Military_Scenario");
                Tag tagTacticalGraphics = tagMilitaryScenario.getTagHijoByName("Tactical_Graphics");
                Tag tagFiguras = tagTacticalGraphics.getTagHijoByName("Figuras");
                Tag tagLineas = tagFiguras.getTagHijoByName("lineas");
                
                 List<Tag> listaLineas =  tagLineas.getTagHijoByName("linea", Tag.Cantidad.TODOS_LOS_TAGS);
                 
                 for(Tag linea: listaLineas)
                 {
                     Tag tagNombreLinea = linea.getTagHijoByName("nombre");
                     Tag tagIdLinea = linea.getTagHijoByName("id");
                     Tag tagColorLinea = linea.getTagHijoByName("color");
                     Tag tagAnchoLinea = linea.getTagHijoByName("ancho");
                     Tag tagCoordenadasLinea = linea.getTagHijoByName("coordenadas");
                     
                     int idLinea = Integer.parseInt(tagIdLinea.getContenido());
                     String nomLinea = tagNombreLinea.getContenido();
                     String colorLinea = tagColorLinea.getContenido();
                     String anchoLinea = tagAnchoLinea.getContenido();
                     
                     List<Tag> listaCoordenadas = tagCoordenadasLinea.getTagHijoByName("coordenada", Tag.Cantidad.TODOS_LOS_TAGS);
                     
                     for(Tag coordenada : listaCoordenadas)
                     {
                         Tag tagItem = coordenada.getTagHijoByName("item");
                         Tag tagLat = coordenada.getTagHijoByName("latitud");
                         Tag tagLong = coordenada.getTagHijoByName("longitud");
                         System.out.println("latitud: "+ tagLat.getContenido());
                         System.out.println("longitud: "+ tagLong.getContenido());
                         int itemCoord = Integer.parseInt(tagItem.getContenido());
                         String latCoord = tagLat.getContenido();
                         String longCoord = tagLong.getContenido();
                         CoordenadasLinea coordenadasLinea = new CoordenadasLinea(itemCoord, latCoord, longCoord);
                         dataCoordLinea.add(coordenadasLinea);
                     }
                     ObservableList<CoordenadasLinea> coordenadasDeEstaLinea = FXCollections.observableArrayList();
                     coordenadasDeEstaLinea.addAll(dataCoordLinea);
                     dataCoordLinea.clear();
                     
                     Lineas lineas = new Lineas(idLinea, nomLinea, colorLinea, anchoLinea, coordenadasDeEstaLinea);
                     
                     datosLinea.add(lineas);
                     tablaLineas.setItems(datosLinea);
                                      
                     System.out.println("El nombre es: "+ tagNombreLinea.getContenido());
                     System.out.println("El id es: "+ tagIdLinea.getContenido());
                     System.out.println("El color es: "+ tagColorLinea.getContenido());
                     System.out.println("El ancho es: "+ tagAnchoLinea.getContenido());
                     
                 }
                
            }catch (TagHijoNotFoundException ex) {
                Logger.getLogger(Panel_MarcadoresController.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ParserConfigurationException ex) {
                Logger.getLogger(Panel_MarcadoresController.class.getName()).log(Level.SEVERE, null, ex);
            } catch (SAXException ex) {
                Logger.getLogger(Panel_MarcadoresController.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(Panel_MarcadoresController.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    if anyone is interested and does not understand the code, ask

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points