I want to get a list of the names of keys stored in a keystore.xml:
<?xml version="1.0" encoding="ISO-8859-1"?>
<keystore>
<key name="key-01">
<Verwendungszweck></Verwendungszweck>
<Generation></Generation>
<Version></Version>
<Algorithmus></Algorithmus>
<Keylength></Keylength>
<Blocklength></Blocklength>
</key>
<key name="key-02">
<Verwendungszweck></Verwendungszweck>
<Generation></Generation>
<Version></Version>
<Algorithmus></Algorithmus>
<Keylength></Keylength>
<Blocklength></Blocklength>
</key>
</keystore>
Unfortunately Netbeans says that it "cannot find symbol keyNameAttribute = keyList.get(i).getAttribute("name");". I don't get why it's not working. Do you have any idea? This is my code:
public List getKeyNames(){
try {
SAXBuilder builder = new SAXBuilder();
Document document = builder.build(f);
List keyNameList = new ArrayList();
List keyList = new ArrayList();
Element keystore = document.getRootElement();
keyList = keystore.getChildren("key");
for(int i=0; i<=keyList.size(); i++) {
keyNameList.add((keyList.get(i)).getAttribute("name").getValue());
}
return keyNameList;
}
catch (JDOMException e) {
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
System.out.println(e.getMessage());
}
return null;
}
Basically, you need to use generics. You're currently using raw types - so keyList.get(i)
is an expression of type Object
. It would also be cleaner to use an enhanced for loop (or Java 8 streams) - currently your for
loop has an inappropriate upper bound anyway.
I suspect you want (pre-Java 8):
List<String> keyNameList = new ArrayList();
Element keystore = document.getRootElement();
for (Element element : keystore.getChildren("key")) {
keyNameList.add(element.getAttribute("name").getValue());
}
(You should declare your method to return a List<String>
too.)
If you're not familiar with generics already, I would strongly recommend that you read up on them immediately. They're a very important part of modern Java programming.
See more on this question at Stackoverflow