The followign is my XML

<?xml version="1.0"?>
<catalog>
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications 
      with XML.</description>
      <add>yes</add>
   </book>
   <book id="bk102">
      <author>Ralls, Kim</author>
      <title>Midnight Rain</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-12-16</publish_date>
      <description>A former architect battles corporate zombies, 
      an evil sorceress, and her own childhood to become queen 
      of the world.</description>
      <add>yes</add>
   </book>
   <book id="bk103">
      <author>Corets, Eva</author>
      <title>Maeve Ascendant</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-11-17</publish_date>
      <description>After the collapse of a nanotechnology 
      society in England, the young survivors lay the 
      foundation for a new society.</description>
      <add>yes</add>
   </book>
   <book id="bk104">
      <author>Corets, Eva</author>
      <title>Oberon's Legacy</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2001-03-10</publish_date>
      <description>In post-apocalypse England, the mysterious 
      agent known only as Oberon helps to create a new life 
      for the inhabitants of London. Sequel to Maeve 
      Ascendant.</description>
      <add>yes</add>
   </book>
   <book id="bk105">
      <author>Corets, Eva</author>
      <title>The Sundered Grail</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2001-09-10</publish_date>
      <description>The two daughters of Maeve, half-sisters, 
      battle one another for control of England. Sequel to 
      Oberon's Legacy.</description>
      <add>yes</add>
   </book>
   <book id="bk106">
      <author>Randall, Cynthia</author>
      <title>Lover Birds</title>
      <genre>Romance</genre>
      <price>4.95</price>
      <publish_date>2000-09-02</publish_date>
      <description>When Carla meets Paul at an ornithology 
      conference, tempers fly as feathers get ruffled.</description>
      <add>yes</add>
   </book>
   <book id="bk107">
      <author>Thurman, Paula</author>
      <title>Splish Splash</title>
      <genre>Romance</genre>
      <price>4.95</price>
      <publish_date>2000-11-02</publish_date>
      <description>A deep sea diver finds true love twenty 
      thousand leagues beneath the sea.</description>
      <add>yes</add>
   </book>
   <book id="bk108">
      <author>Knorr, Stefan</author>
      <title>Creepy Crawlies</title>
      <genre>Horror</genre>
      <price>4.95</price>
      <publish_date>2000-12-06</publish_date>
      <description>An anthology of horror stories about roaches,
      centipedes, scorpions  and other insects.</description>
      <add>yes</add>
   </book>
   <book id="bk109">
      <author>Kress, Peter</author>
      <title>Paradox Lost</title>
      <genre>Science Fiction</genre>
      <price>6.95</price>
      <publish_date>2000-11-02</publish_date>
      <description>After an inadvertant trip through a Heisenberg
      Uncertainty Device, James Salway discovers the problems 
      of being quantum.</description>
      <add>yes</add>
   </book>
   <book id="bk110">
      <author>O'Brien, Tim</author>
      <title>Microsoft .NET: The Programming Bible</title>
      <genre>Computer</genre>
      <price>36.95</price>
      <publish_date>2000-12-09</publish_date>
      <description>Microsoft's .NET initiative is explored in 
      detail in this deep programmer's reference.</description>
      <add>yes</add>
   </book>
   <book id="bk111">
      <author>O'Brien, Tim</author>
      <title>MSXML3: A Comprehensive Guide</title>
      <genre>Computer</genre>
      <price>36.95</price>
      <publish_date>2000-12-01</publish_date>
      <description>The Microsoft MSXML3 parser is covered in 
      detail, with attention to XML DOM interfaces, XSLT processing, 
      SAX and more.</description>
      <add>yes</add>
   </book>
   <book id="bk112">
      <author>Galos, Mike</author>
      <title>Visual Studio 7: A Comprehensive Guide</title>
      <genre>Computer</genre>
      <price>49.95</price>
      <publish_date>2001-04-16</publish_date>
      <description>Microsoft Visual Studio 7 is explored in depth,
      looking at how Visual Basic, Visual C++, C#, and ASP+ are 
      integrated into a comprehensive development 
      environment.</description>
      <add>yes</add>-
   </book>
</catalog>

I am using an DOM parser to parse and I have put the xml in an hashMap.
ie., HashMap<String, HashMap<String,String> to represent the id and the tag values in another hashmap , now when I am trying to iteratethorugh the hashmap it is only showing the last value in the hashmap.THe below is the code snippet, kindly advise where I am going wrong

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package domparser;



import java.util.HashMap;
import java.util.Iterator;
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;


/**
 *
 * @author Shreeansh Suman
 */
public class Domparser 
{

    public static HashMap<String,String> hmDetails = new HashMap<String,String>();
    public static HashMap<String,HashMap<String,String>> hmData = new HashMap<String,HashMap<String,String>>();
    public static String bookRootElement ;


    public static void main(String[] args) 
    {
        HashMap<String,String> detailsHM = new HashMap<String,String>();
        try
        {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc =db.parse("E:\\dd\\books.xml");
        NodeList booknodelist = doc.getElementsByTagName("book");
        int size = booknodelist.getLength();

        for( int i =0; i < size; i++)
        {
           Node booknode= booknodelist.item(i);
           if(booknode.getNodeType() == Element.ELEMENT_NODE)
           {
                Element bookElement =(Element)booknode;
                bookRootElement = bookElement.getAttribute("id");
                //System.out.println("bookRootElement" +" :" +bookRootElement);
                NodeList bookChildNodes = bookElement.getChildNodes();

                for( int j =0 ; j<bookChildNodes.getLength(); j++)
                {
                     Node bookNodeElement = bookChildNodes.item(j);
                     if( bookNodeElement.getNodeType() == Element.ELEMENT_NODE)
                     {
                          Element elementNodeBook = (Element)bookNodeElement;
                         // System.out.println(elementNodeBook.getTagName() + " : " + elementNodeBook.getTextContent());
                          hmDetails.put(elementNodeBook.getTagName(), elementNodeBook.getTextContent());
                     }


                }

           }



        }
         for( String str : hmData.keySet())
           {
               System.out.println(str + hmData.get(str));
           }

//        Iterator<String> itrKey =hmData.keySet().iterator();
//        while(itrKey.hasNext())
//        {
//            String bookId = itrKey.next();
//            System.out.println("BookID" +" :"+ bookId+ " ");
//            detailsHM = hmData.get(bookId);
//            for( String tag : detailsHM.keySet())
//            {
//                String content = detailsHM.get(tag);
//                System.out.println(" Key" + " :" + tag +" :"+ "COntent" +" :"+ content);
//            }
//            
//        }

        }
        catch(Exception ex)
        {
            System.out.println(ex.getMessage());
        }


    }

}

After a quick look at that code I see three HashMaps. Only one seems to get anything put in it, and only one (not the same) gets printed. Makes no sense to me.

probably yes. I have remodeled and it is working and i need to extend it to add this to the jtable.
The reason why i am using the third HM is

 Iterator<String> itr = hmData.iterator();
 while( itr.hasNext())
 {
  String str =  itr.next() //will get the key from the hashmap
  //third hasmap is to use get the value from the key which is the hashmap
  detailsHm = hmData.get(str);
   while iterating  add the data to the vector and add it as an row to the table.


 }




package domparser;

import java.util.HashMap;
import java.util.Iterator;

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 Domparser
{

       public static HashMap<String,String>hmDetails = new HashMap<String,String>();
       public static HashMap<String,HashMap<String,String>> hmData = new HashMap<String, HashMap<String,String>>();
       public String tagElementkey;
       public String tagContentvalue;
       public static String bookid;

       public static void mapIteration(HashMap<String,HashMap<String,String>> hmData)
       {

              String bId = null ;
              HashMap<String,String> dataHm = new HashMap<String,String>();

              Iterator<String> itrset =hmData.keySet().iterator();
              while(itrset.hasNext())
              {
                       bId = itrset.next();

                       dataHm = hmData.get(bId); 
                       //System.out.println("BID" +" :"+ bId);


               }

               System.out.println("bookId"+":"+ bookid);
              for( String str : dataHm.keySet())
              {
                     System.out.println(str+"--"+dataHm.get(str));
              }



       }

       public static void treeToHashMap()
       {

              try
              {

                     DocumentBuilderFactory dbf =DocumentBuilderFactory.newInstance();
                     DocumentBuilder db =dbf.newDocumentBuilder();

                     Document doc =db.parse("E:\\dd\\books.xml");

                     NodeList booknodelist =doc.getElementsByTagName("book");
                     int size = booknodelist.getLength();


                     for( int i =0; i<booknodelist.getLength(); i++)
                     {
                           Node booknode =booknodelist.item(i);

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

                                  Element nodebook = (Element) booknode;

                                  bookid =nodebook.getAttribute("id");

                                  NodeList nodelistbook = nodebook.getChildNodes();


                                  for( int j=0 ; j< nodelistbook.getLength(); j++)
                                  {
                                         Node current = nodelistbook.item(j);

                                         if( current.getNodeType() == Node.ELEMENT_NODE)

                                         {

                                                Element ele = (Element)current;

                                                hmDetails.put(ele.getTagName(), ele.getTextContent());

                                         }



                                  }



                           }

                           //hmDetails.put(tagElementkey, tagContentvalue);
                           /*for(String sr : hmDetails.keySet())
                           {
                                  System.out.println(sr + " :" +hmDetails.get(sr));
                           } */

                           hmData.put(bookid, hmDetails);

                           mapIteration(hmData);
                     }




              }

       catch(Exception ex)
       {

              System.out.println(ex.getMessage());
       }


}


       public static void main(String[] args)
       {

              treeToHashMap();



       }

}

As far as I can see you need a variable (pointer) when retrieving the values (line 6), but not another HashMap.

The ideal way to parse the xml elements from the xml file and display the node elements in the JTable. Here is the code as below

 package domparser;

    import java.awt.BorderLayout;
    import java.awt.EventQueue;

    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.border.EmptyBorder;
    import javax.swing.JScrollPane;
    import java.awt.GridLayout;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableModel;
    import java.awt.Dimension;
    import java.awt.Window.Type;

    public class Domparsergui extends JFrame {

        private JPanel contentPane;
        private static JTable table;

        /**
         * Launch the application.
         */
        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {
                public void run() {
                    try {
                        Domparsergui frame = new Domparsergui();
                        frame.setVisible(true);
                        Domparser.treeToHashMap(table);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        /**
         * Create the frame.
         */
        public Domparsergui() {
            setType(Type.UTILITY);
            setTitle("Books ");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setBounds(100, 100, 958, 361);
            contentPane = new JPanel();
            contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
            setContentPane(contentPane);
            contentPane.setLayout(null);

            JPanel panel = new JPanel();
            panel.setSize(new Dimension(10, 10));
            panel.setBounds(0, 0, 880, 184);
            contentPane.add(panel);
            panel.setLayout(new GridLayout(1, 0, 0, 0));

            JScrollPane scrollPane = new JScrollPane();
            panel.add(scrollPane);

            table = new JTable();
            table.setSize(new Dimension(100, 100));
            table.setToolTipText("");
            table.setModel(new DefaultTableModel(
                new Object[][] {
                },
                new String[] {
                    "Author", "Title", "Genre", "Price", "Publish Date", "Description"
                }
            ));
            scrollPane.setViewportView(table);

        }
    }

Parser code

package domparser;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.StringTokenizer;
import java.util.Vector;

import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
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 Domparser
{

       public static HashMap<String,String>hmDetails = new HashMap<String,String>();
       public static HashMap<String,HashMap<String,String>> hmData = new HashMap<String, HashMap<String,String>>();
       public String tagElementkey;
       public String tagContentvalue;
       public static String bookid;
       //public static Vector<String> vData = new Vector<String>();
       public static ArrayList<Books> alFields = new ArrayList<Books>();
       public static Books b;
       public static JTable domTable;

       public static void mapIteration(HashMap<String,HashMap<String,String>> hmData, JTable table)
       {
              domTable = table;
              String bId = null ;
              HashMap<String,String> dataHm = new HashMap<String,String>();

              //DefaultTableModel tableModel =  (DefaultTableModel)domTable.getModel();



              Iterator<String> itrset =hmData.keySet().iterator();
              while(itrset.hasNext())
              {
                       bId = itrset.next();

                       dataHm = hmData.get(bId); 

               }

              populateTable(dataHm, domTable);




       }

       public static void populateTable(HashMap<String,String> dataHm, JTable domTable) 
       {

           String[] col= {"Author", "Title", "Genre", "Price", "Publish Date", "Description"};
           alFields = new ArrayList<Books>();

           for( String st : dataHm.keySet())
            {
                String author=dataHm.get("author");
                String title =dataHm.get("title");
                String genre =dataHm.get("genre");
                String price = dataHm.get("price");
                String publish_date = dataHm.get("publish_date");
                String description = dataHm.get("description");

                b= new Books(author, title, genre, price,publish_date,description); 

            }

           alFields.add(b);               


        DefaultTableModel dmt = (DefaultTableModel)domTable.getModel();
          // DefaultTableModel dmt = new DefaultTableModel(col, 0);




            for( int i =0; i<alFields.size(); i++)
            {
                String author = alFields.get(i).getAuthor();
                String title = alFields.get(i).getTitle();
                String price = alFields.get(i).getPrice();
                String genre = alFields.get(i).getGenre();
                String  publish_date = alFields.get(i).getPublish_date();
                String desc = alFields.get(i).getDescription();

                //str = sb.append(author).append(",").append(title).append(",").append(genre).append(",").append(price).append(",").append(publish_date).append(",").append(desc).toString();
                //System.out.println(str);
                Object[] data = {author,title,genre,price,publish_date,desc};
                dmt.addRow(data);

            }

              ColumnAdjuster ca = new ColumnAdjuster(domTable);
              ca.adjustColumns();


       }

    /*public static ArrayList<String> convertStringToArrayList(String str, String delim)
    {

        ArrayList<String> elements = new ArrayList<String>();
        StringTokenizer stkn = new StringTokenizer(str,delim,false);

        while(stkn.hasMoreTokens())
        {
            String token = stkn.nextToken();
            elements.add(token);
        }

        return elements;

    }  */

       public static void treeToHashMap(JTable table)
       {

              try
              {

                     DocumentBuilderFactory dbf =DocumentBuilderFactory.newInstance();
                     DocumentBuilder db =dbf.newDocumentBuilder();

                     Document doc =db.parse("E:\\dd\\books.xml");

                     NodeList booknodelist =doc.getElementsByTagName("book");
                     int size = booknodelist.getLength();


                     for( int i =0; i<booknodelist.getLength(); i++)
                     {
                           Node booknode =booknodelist.item(i);

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

                                  Element nodebook = (Element) booknode;

                                  bookid =nodebook.getAttribute("id");

                                  NodeList nodelistbook = nodebook.getChildNodes();


                                  for( int j=0 ; j< nodelistbook.getLength(); j++)
                                  {
                                         Node current = nodelistbook.item(j);

                                         if( current.getNodeType() == Node.ELEMENT_NODE)

                                         {

                                                Element ele = (Element)current;

                                                hmDetails.put(ele.getTagName(), ele.getTextContent());

                                         }



                                  }



                           }

                           //hmDetails.put(tagElementkey, tagContentvalue);
                           /*for(String sr : hmDetails.keySet())
                           {
                                  System.out.println(sr + " :" +hmDetails.get(sr));
                           } */

                           hmData.put(bookid, hmDetails);

                           mapIteration(hmData, table);
                     }




              }

       catch(Exception ex)
       {

              System.out.println(ex.getMessage());
       }


}



}

The books.java class that will convert each element into an object

Column Adjuster code that will adjust the columns while displaying.

import java.util.Date;

public class Books 
{



     private String author;
     private String title;
     private String genre;
     private String price;
     private String publish_date;
     private String description;

    public Books(String author, String title, String genre, String price, String publish_date, String description) 
    {
        super();
        this.author = author;
        this.title = title;
        this.genre = genre;
        this.price = price;
        this.publish_date = publish_date;
        this.description = description;
    }
    /**
     * @return the author
     */
    public String getAuthor() 
    {
        return author;
    }
    /**
     * @return the title
     */
    public String getTitle() {
        return title;
    }
    /**
     * @return the genre
     */
    public String getGenre() {
        return genre;
    }
    /**
     * @return the price
     */
    public String getPrice() {
        return price;
    }
    /**
     * @return the publish_date
     */
    public String getPublish_date() {
        return publish_date;
    }
    /**
     * @return the description
     */
    public String getDescription() {
        return description;
    }
    /**
     * @param author the author to set
     */
    public void setAuthor(String author) {
        this.author = author;
    }
    /**
     * @param title the title to set
     */
    public void setTitle(String title) {
        this.title = title;
    }
    /**
     * @param genre the genre to set
     */
    public void setGenre(String genre) {
        this.genre = genre;
    }
    /**
     * @param price the price to set
     */
    public void setPrice(String price) {
        this.price = price;
    }
    /**
     * @param publish_date the publish_date to set
     */
    public void setPublish_date(String publish_date) {
        this.publish_date = publish_date;
    }
    /**
     * @param description the description to set
     */
    public void setDescription(String description) {
        this.description = description;
    }
    /* (non-Javadoc)
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return "Books [author=" + author + ", title=" + title + ", genre=" + genre + ", price=" + price
                + ", publish_date=" + publish_date + ", description=" + description + "]";
    }



}




/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package domparser;

import java.awt.Component;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;

/**
 *
 * @author 
 */
public class ColumnAdjuster {
    JTable table;
    int spacing = 3;
    public ColumnAdjuster(JTable tableObj) {
        this.table = tableObj;
    }

    public void adjustColumns() {
        TableColumnModel colModelObj = table.getColumnModel();
        int iColCount = colModelObj.getColumnCount();
        for(int i = 0; i < iColCount; i++) {
             adjustColumn(i);
        }
    }

    public void adjustColumn(int colIndex) {
        TableColumn tableColumn = table.getColumnModel().getColumn(colIndex);
        int columnHeaderWidth = getColumnHeaderWidth(colIndex);
        int columnDataWidth   = getColumnDataWidth(colIndex);
        int preferredWidth    = Math.max(columnHeaderWidth, columnDataWidth);
        updateTableColumn(colIndex, preferredWidth);
    }

    private int getColumnHeaderWidth(int colIndex) {
        TableColumn tableColumn = table.getColumnModel().getColumn(colIndex);
        Object value = tableColumn.getHeaderValue();
        TableCellRenderer renderer = tableColumn.getHeaderRenderer();
        if (renderer == null) {
            renderer = table.getTableHeader().getDefaultRenderer();
        }
        Component c = renderer.getTableCellRendererComponent(table, value, false, false, -1, colIndex);
        return c.getPreferredSize().width;
    }        

    private int getColumnDataWidth(int colIndex) {
        int preferredWidth = 0;
        int maxWidth = table.getColumnModel().getColumn(colIndex).getMaxWidth();
        int iRowCount = table.getRowCount();
        for (int rowIndex = 0; rowIndex < iRowCount; rowIndex++) {
            preferredWidth = Math.max(preferredWidth, getCellDataWidth(rowIndex, colIndex));
            if (preferredWidth >= maxWidth) {
                    break;
            }
        }
        return preferredWidth;
    }

    private int getCellDataWidth(int rowIndex, int colIndex) {
        TableCellRenderer cellRenderer = table.getCellRenderer(rowIndex, colIndex);
        Component c = table.prepareRenderer(cellRenderer, rowIndex, colIndex);
        int width = c.getPreferredSize().width + table.getIntercellSpacing().width;
        return width;
    }

    private void updateTableColumn(int colIndex, int width) {
        TableColumn tableColumn = table.getColumnModel().getColumn(colIndex);
        width += spacing;
        table.getTableHeader().setResizingColumn(tableColumn);
        tableColumn.setWidth(width);
    }   
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.