gpt4 book ai didi

java - 从 java 中的文档生成器列表中删除重复的 xml 元素

转载 作者:行者123 更新时间:2023-11-30 11:10:15 24 4
gpt4 key购买 nike

这是我正在尝试做的事情:

  • 加载 XML 文件,然后扫描 XML 文件以将所有元素放入组合框中,以便用户可以选择一个。

事实上,在 XML 文件本身的主体中有几个具有相同标签的元素,因此,该元素在下拉列表中出现不止一次,是在我的 for 循环中有一种方法可以比较已经存在的内容并删除重复项吗?

这是我得到的整个方法

     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();
}
}


编辑:

我面临的第二个问题是确保所有元素都按字母顺序排列。我通过执行以下操作解决了这个问题:

// 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);
}

最佳答案

声明一个ArrayList,

如果您使用的是 Java 7,

        ArrayList<String> allValues = new ArrayList<>();

或者如果您使用的是早期版本的 Java,

        ArrayList<String> allValues = new ArrayList<String>();

在你的 for 循环中,

           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);
}
}

关于java - 从 java 中的文档生成器列表中删除重复的 xml 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27783572/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com