Here's what I'm trying to do:
I've got this working up to a point in the fact that there are several elements with the same tags within the body of the XML file itself, and thus, the element occurs more than once in the drop down list, is there a way in my for loop to compare what's already there and remove duplicates?
Here's the entire method I've got
public static void readXML(String filePath) {
try {
//Gets selected XML file
File XmlFile = new File(filePath);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(XmlFile);
//Searches all text
doc.getDocumentElement().normalize();
//Make a non-editable combo box
JComboBox<String> comboBox = new JComboBox<String>();
comboBox.setEditable(false);
//Get all the XML elements from the file
NodeList list = doc.getElementsByTagName("*");
//TODO:
//Make sure all XML elements only appear once in the list
//Populate combobox with all elements from input file
for (int i = 0; i < list.getLength(); i++) {
Element element = (Element)list.item(i);
String item = element.getNodeName().toString();
//Add comparison here??
comboBox.addItem(item);
}
//Add Combo box and refresh the frame window so that it appears
buttonPanel.add(comboBox);
frame.revalidate();
//Add action listener show which XML element has been selected
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
//Get the source of the component, which is the combo box
JComboBox<?> comboBox = (JComboBox<?>) event.getSource();
//Print the selected item
String selected = comboBox.getSelectedItem().toString();
log.append("The selected XML element is: " + selected + newline);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
EDIT:
A second problem I faced was to make sure that all the elements were in alphabetical order. I fixed this issue by doing the following:
// Make a sublist so that the elements can be sorted
List<String> subList = allValues.subList(0, allValues.size());
Collections.sort(subList);
// Add the items from the subList to the comboBox
for (int j = 0; j < subList.size(); j++) {
String listItem = subList.get(j).toString();
comboBox.addItem(listItem);
}
declare an ArrayList,
If you are using Java 7,
ArrayList<String> allValues = new ArrayList<>();
or if you are using earlier version of Java,
ArrayList<String> allValues = new ArrayList<String>();
inside your for
loop,
for (int i = 0; i < list.getLength(); i++) {
Element element = (Element)list.item(i);
String item = element.getNodeName().toString();
if (!allValues.contains(item)){
comboBox.addItem(item);
allValues.add(item);
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments