How to count the number of options in a select DOM Element in Java

Hi folks is there a way to count the number of options in a select DOM Element retrieved using JSoup or Java by itself after having the file saved in a text file?
Any help with this would be appreciated.
Cheers!
Rodric MacOliverResearcherAsked:
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.

CEHJCommented:
'Elements' is essentially a List, so the size() method can be used if you reverse the 'serialization' process
0
Rodric MacOliverResearcherAuthor Commented:
How would I go about using the size function?
0
Rodric MacOliverResearcherAuthor Commented:
How would I go about using the size function?
If I try
"System.out.print(chapters.size());"
I get 0 even though I was supposed to get 16...
0
Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

CEHJCommented:
You'd have to show me that in context
0
Rodric MacOliverResearcherAuthor Commented:
CEHJ, here is the code I'm using for you to have a look:
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jsoup.Jsoup;
import org.jsoup.helper.Validate;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.FileReader;


public class NewJFrame extends javax.swing.JFrame {

    /**
     * Creates new form NewJFrame
     */
    public NewJFrame() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        ffNumber = new javax.swing.JTextField();
        receiveTitle = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenu2 = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("Check Title");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jMenu1.setText("File");
        jMenuBar1.add(jMenu1);

        jMenu2.setText("Edit");
        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(38, 38, 38)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(receiveTitle, javax.swing.GroupLayout.PREFERRED_SIZE, 366, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(ffNumber, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton1)))
                .addContainerGap(294, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(33, 33, 33)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(ffNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(receiveTitle, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(336, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    public static String html2text(String html) {
                return Jsoup.parse(html).text();
            }
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        try {
            // TODO add your handling code here:
            int storyId = Integer.parseInt(ffNumber.getText());
            String address = "https://www.mysite.com/9475375/1/";
            Document doc = Jsoup.connect(address).get();
            String title = doc.title();
            String text = doc.body().text();
            Elements info = doc.select("div#storycontent");            
            
            //Receive Chapters from Jump Menu?????
            Elements chapters = doc.select("#jump");
            System.out.print(chapters.size());//not working!!!!!!
                   
            File file = new File("./"+storyId+".txt");
            
            if (!file.exists()) {
				file.createNewFile();
			}
                        //The true below is to indicate that the Append should be used
                        String content = info.toString();
                        content = html2text(content);
			FileWriter fw = new FileWriter(file.getAbsoluteFile());//add,true before last parenteses to adicionar ao final
			BufferedWriter bw = new BufferedWriter(fw);
                        //bw.write(info.toString());
			bw.write(content);                        
			bw.close();
 
			System.out.println();
                        receiveTitle.setText(title+" Done");
                        
            
        } catch (IOException ex) {
            Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
    }                                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewJFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JTextField ffNumber;
    private javax.swing.JButton jButton1;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JLabel receiveTitle;
    // End of variables declaration                   
}

Open in new window

Cheers!
0
CEHJCommented:
I'd need to test that but i can't connect to that URL
0
Rodric MacOliverResearcherAuthor Commented:
Its not online yet, I'm just using on a local server...

The select would be something like the following if that helps...

<select name="jump" id="jump" onchange="var c = this.selectedIndex; if(c > 0) self.location = '/s/5957714/'+c+'/'"><option selected="selected" value="0">Jump:</option><option value="1">Chapter 1</option><option value="2">Chapter 2</option><option value="3">Chapter 3</option><option value="4">Chapter 4</option><option value="5">Chapter 5</option><option value="6">Chapter 6</option><option value="7">Chapter 7</option><option value="8">Chapter 8</option><option value="9">Chapter 9</option><option value="10">Chapter 10</option><option value="11">Chapter 11</option><option value="12">Chapter 12</option><option value="13">Chapter 13</option><option value="14">Chapter 14</option><option value="15">Chapter 15</option><option value="16">Chapter 16</option><option value="17">Chapter 17</option><option value="18">Chapter 18</option><option value="19">Chapter 19</option><option value="20">Chapter 20</option><option value="21">Chapter 21</option><option value="22">Chapter 22</option><option value="23">Chapter 23</option><option value="24">Chapter 24</option><option value="25">Chapter 25</option><option value="26">Chapter 26</option><option value="27">Chapter 27</option><option value="28">Chapter 28</option><option value="29">Chapter 29</option><option value="30">Chapter 30</option><option value="31">Chapter 31</option><option value="32">Chapter 32</option><option value="33">Chapter 33</option><option value="34">Chapter 34</option><option value="35">Chapter 35</option><option value="36">Chapter 36</option><option value="37">Chapter 37</option><option value="38">Chapter 38</option><option value="39">Chapter 39</option><option value="40">Chapter 40</option><option value="41">Chapter 41</option><option value="42">Chapter 42</option><option value="43">Chapter 43</option><option value="44">Chapter 44</option><option value="45">Chapter 45</option><option value="46">Chapter 46</option><option value="47">Chapter 47</option><option value="48">Chapter 48</option><option value="49">Chapter 49</option><option value="50">Chapter 50</option></select>

Open in new window

0
CEHJCommented:
select#jump would be the key then, not #jump
0
mccarlIT Business Systems Analyst / Software DeveloperCommented:
Firstly...

I get 0 even though I was supposed to get 16...
That is a worry because you should have at least got the value 1 (because your code is asking to return an element with "id" of "jump", and there is only 1 of those). You have indicated that the HTML that you posted is "something like" what the real HTML is but when I do the same select("#jump") on this example HTML that you posted, I get the correct value of 1. So there must still be a difference between that example and the real HTML that you are testing with, in order for it to return 0.

So you need to look into why that is the case... (maybe post the ACTUAL html that you are testing with)

Once that is sorted, you then need to change your select query method call to select the "option" elements within the #jump select element. The below code correctly returns the value 51 for the example HTML that you posted above.

import java.io.File;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;


public class TestJSoup {
    
    public static void main(String[] args) throws Exception {
        Document doc = Jsoup.parse(new File("input.html"), null);
        Elements chapters = doc.select("#jump option");
        System.out.println(chapters.size());
    }
    
}

Open in new window

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
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.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.