How to save select checkbox items to an XML file in Java?

Hi,
I have java code and this code creates GUI. In this GUI. I have check boxes in a Tree.

The thing that I would like to do is to save the selected check box items to an XML file.

This is the class and the methods that I use to create the tree with check boxes:

public class CheckListTree {
    private Tree tree;
    private static CheckListTree instance = null;
   
    
    private CheckListTree() {
    }
    
    public static CheckListTree getInstance()
    {
        if (instance == null) {
            instance = new CheckListTree();
        }
        //System.out.println("instance: " + instance);
        return instance;
    }
    
    
    public void unselectAll (){
        System.out.println("tree: " + tree);
        for (TreeItem item : tree.getItems()) {   
            //System.out.println("item: " + item);
            checkItems(item, false);
        }
        
    }
    
    public void checkPath(TreeItem item, boolean checked, boolean grayed) {
        if (item == null) return;
        if (grayed) {
            checked = true;
        } else {
            int index = 0;
            TreeItem[] items = item.getItems();
            while (index < items.length) {
                TreeItem child = items[index];
                if (child.getGrayed() || checked != child.getChecked()) {
                    checked = grayed = true;
                    break;
                }
                index++;
            }
        }
        item.setChecked(checked);
        item.setGrayed(grayed);
        checkPath(item.getParentItem(), checked, grayed);
    }

    public void checkItems(TreeItem item, boolean checked) {
        item.setGrayed(false);
        item.setChecked(checked);
        TreeItem[] items = item.getItems();
        for (int i = 0; i < items.length; i++) {
            checkItems(items[i], checked);
        }
    }

    public void createCheckListTree(Composite compTab2, GridData layoutData, List<HashMap<Integer, String>> checkList)  {
            tree = new Tree(compTab2, SWT.BORDER | SWT.CHECK);
            tree.setLayoutData(layoutData);
            tree.addListener(SWT.Selection, new Listener() {
                public void handleEvent(Event event) {
                    if (event.detail == SWT.CHECK) {
                        TreeItem item = (TreeItem) event.item;
                        boolean checked = item.getChecked();
                        checkItems(item, checked);
                        checkPath(item.getParentItem(), checked, false);
                    }
                }
            });
                  
            
            TreeItem item_Standards = new TreeItem(tree, SWT.NONE);
            item_Standards.setText("My List");
            
            Iterator<HashMap<Integer, String>> checkListIter = checkList.iterator();
            while(checkListIter .hasNext()) {
              HashMap<Integer, String> amap =   (HashMap<Integer, String>) checkListIter .next();
              Set<?> keysetString = (Set<?>) amap .keySet();
              Iterator<?> iter = keysetString.iterator();
              while( iter.hasNext() ) {
                Integer keyVal = (Integer) iter.next();
                //System.out.println("keyVal " + keyVal);
                String valFromKey = amap.get(keyVal);
                //System.out.println("valFromKey " + valFromKey);
                TreeItem item_Substandards = new TreeItem(item_Standards, SWT.NONE);
                item_Substandards.setText(valFromKey);
              } 
            }
    } 
    
    public void saveCheckedList2XML(){
    //HERE I WANT TO SAVE THE SELECTED ITEMS TO A PLACE of USER'S choice   
        
    }

Open in new window


This is the listener I use for this button:

        }else if(toolItem == Gui.item222){
            CheckListTree.getInstance().saveCheckedList2XML();

Open in new window


Can you please help me how I can do it in my code above?

Thanks
TolgarAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

TolgarAuthor Commented:
Actually, I made some change in the structure:

The toolbar listener will be like this:

        }else if(toolItem == Gui.item222){
            FileDialog dlg = new FileDialog(shell);
            String file = dlg.open();
            //System.out.println("chosen file : " + file);
            if (file!=null && !file.equals("")){
                CheckListTree.getInstance().getCheckedStandards(file);
            } 

Open in new window


And the methods in the CheckListTree class will be as the following:

    public void write2XML(String content, String file) {
        //HERE WE WILL WRITE THE CONTENT TO AN XML FILE
    }
    
    public void getCheckedStandards(String file){
        //HERE WE WILL GET THE LIST OF CHECKED ITEMS FROM THE TREE
        
        write2XML(content, file);              
    }

Open in new window

0
TolgarAuthor Commented:
so, I did the getCheckedStandards method as shown below:

    public void write2XML(TreeItem[] content, String fileName) {
        
    }
    
    public void getCheckedStandards(String file){
        TreeItem[] items = tree.getSelection();
        
        for (int i = 0; i < items.length; i++) {
            TreeItem[] child = items[i].getItems();
            for (int index=0; index < child.length; index++) { 
                if (child[index].getChecked()) {
                    System.out.println("item: " + index + ": " + child[index].getText());
                }
            }
        }
        //write2XML(item, file);              
    }

Open in new window


Can you please show me how I can do write2XML method?

Thanks,
0
mccarlIT Business Systems Analyst / Software DeveloperCommented:
You would need to tell us exactly what information is in the tree and what part of that info needs to go into the file. A good way to go about it, is to show a made up example of what the tree would look like and also give a made up XML file that shows what you would expect to be built based on that example tree.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Learn Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

TolgarAuthor Commented:
The tree (with checkboxes on the left of each item including Employees. x refers to a check box) looks like this:

x Employees
   x Jack
   x Phil
   x John
   x Susan
   x Jeff

Open in new window


The XML will be like this

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Company>
<Employees>
<Name>
Jack
</Name>
<Name>
Phil
</Name>
<Name>
John
</Name>
<Name>
Susan
</Name>
Jeff
</Employees>
</Company>

Open in new window

0
TolgarAuthor Commented:
The "Employees" node comes from items ith element that I mentioned in my previous post (ID: 39468335). After line 8 in that post, items ( in this case it will be items 0th because there is nothing else other than "employees" at that level), will be written maybe to an hash array and then child[index].getText() will be written to the same hash array at line 12 in the same code that I posted.

Then write2XML will be called with inputs arguments of this hash array and the file.

And, the sudo code will be like this:

    public void write2XML(TreeItem[] content, String fileName) {
        
    }
    
    public void getCheckedStandards(String file){
        TreeItem[] items = tree.getSelection();
        
        for (int i = 0; i < items.length; i++) {
            //IN HERE, WRITE items[i] node to an hash array in here at the top level. 
            //In the example xml, this will be the "Employees" node.
            TreeItem[] child = items[i].getItems();
            for (int index=0; index < child.length; index++) { 
                if (child[index].getChecked()) {
                    // IN HERE, WRITE the name node with the value
                   // of child[index].getText() in the hash array as the child of the "Employees" node. In the example xml, the values of Jack, Phil,
                   //John, Susan, Jeff will be put in the name nodes                 
                    System.out.println("item: " + index + ": " + child[index].getText());
                }
            }
        }    
          //THEN CALL write2XML method with the input values of hash array and file.
    }

Open in new window



Then we need to loop through the hash array in write2XML while writing to the XML file.


And for write2XML, I have this code in place but it only writes one input to the XML. It does not loop through an hash array:

    public void write2XML(String content, String file) {

        try {
   
          DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
          DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
   
          // root elements
          Document doc = docBuilder.newDocument();
          Element rootElement = doc.createElement("Company");
          doc.appendChild(rootElement);
   
          // staff elements
          Element staff = doc.createElement("Employees");
          rootElement.appendChild(staff);
   
          // firstname elements
          Element firstname = doc.createElement("Name");
          firstname.appendChild(doc.createTextNode(content));
          staff.appendChild(firstname);

   
          // write the content into xml file
          TransformerFactory transformerFactory = TransformerFactory.newInstance();
          Transformer transformer = transformerFactory.newTransformer();
          DOMSource source = new DOMSource(doc);
          StreamResult result = new StreamResult(file);
   
          transformer.transform(source, result);
   
          System.out.println("File saved!");
   
        } catch (ParserConfigurationException pce) {
            pce.printStackTrace();
        } catch (TransformerException tfe) {
            tfe.printStackTrace();
        }
    }

Open in new window



How can I do this in Java with these codes?
0
TolgarAuthor Commented:
Ok. I did something to solve this question but I am getting the following error:

Exception in thread "main" java.lang.ClassCastException: org.eclipse.swt.widgets.TreeItem cannot be cast to java.lang.String

Open in new window


And this is the code that I used:

    public void write2XML(Map<Integer, TreeItem> checkListMap, Map<Integer, String> checkNameMap, String file) {
        Iterator<Entry<Integer, TreeItem>> it_checkListMap = checkListMap.entrySet().iterator();
        Iterator<Entry<Integer, String>> it_checkNameMap = checkNameMap.entrySet().iterator();
        
        try {
   
          DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
          DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
   
          // root elements
          Document doc = docBuilder.newDocument();
          Element rootElement = doc.createElement("Company");
          doc.appendChild(rootElement);
          while (it_checkListMap.hasNext()){
              Map.Entry pairs_checkListMap = (Map.Entry)it_checkListMap.next();
              // staff elements
              Element checkList = doc.createElement("Checks");
              checkList.appendChild(doc.createTextNode(StringConverter<pairs_checkListMap.getValue()>));
              rootElement.appendChild(checkList);
              
              while(it_checkNameMap.hasNext()){
                  // firstname elements
                  Element CheckName = doc.createElement("Name");
                  CheckName.appendChild(doc.createTextNode((String) pairs_checkListMap.getValue()));
                  checkList.appendChild(CheckName);
              }

          }
          // write the content into xml file
          TransformerFactory transformerFactory = TransformerFactory.newInstance();
          Transformer transformer = transformerFactory.newTransformer();
          DOMSource source = new DOMSource(doc);
          StreamResult result = new StreamResult(file);
   
          transformer.transform(source, result);
   
          System.out.println("File saved!");
   
        } catch (ParserConfigurationException pce) {
            pce.printStackTrace();
        } catch (TransformerException tfe) {
            tfe.printStackTrace();
        }
    }
    
    
    public void getCheckedStandards(String file){
        TreeItem[] items = tree.getSelection();
        
        final Map<Integer, TreeItem> checkListMap;
        checkListMap = new HashMap<Integer, TreeItem>();
        
        final Map<Integer, String> checkNameMap;
        checkNameMap = new HashMap<Integer, String>();
        
        for (int i = 0; i < items.length; i++) {
            checkListMap.put(i, items[i]);
            //System.out.println("itemS: " + items[0]); 
            TreeItem[] child = items[i].getItems();
            for (int index=0; index < child.length; index++) { 
                if (child[index].getChecked()) {
                    System.out.println("item: " + index + ": " + child[index].getText()); 
                    checkNameMap.put(index, child[index].getText());
                }
            }
        }  
        write2XML(checkListMap, checkNameMap, file);
    }
    
}

Open in new window

0
TolgarAuthor Commented:
I almost never choose average as the score but I didn't hear back from any expert after I responded their question to clarify my question.
0
mccarlIT Business Systems Analyst / Software DeveloperCommented:
I almost never choose average as the score
Not a problem, it seems appropriate here as you seem to have found the solution on your own before I could return to your question. Also, just to let you know that since all the experts here contibute on a volunteer basis, sometimes it may take a number of days to reply. And, at least in my case, over the weekend it is less likely that I would be able to get back to you. I realise that that could be frustrating when all you want to do is to get a solution to your problem but that's just the nature of a system like this. Anyway, I am glad that you were able to work it out for yourself! :)
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.