我想获取存储在 keystore.xml 中的 key 名称列表:
<?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>
不幸的是,Netbeans 说它“找不到符号 keyNameAttribute = keyList.get(i).getAttribute("name");”。我不明白为什么它不起作用。你有什么主意吗?这是我的代码:
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;
}
最佳答案
基本上,您需要使用泛型。您当前正在使用原始类型 - 所以 keyList.get(i)
是 Object
类型的表达式。使用增强的 for 循环(或 Java 8 流)也会更干净 - 目前您的 for
无论如何,循环都有一个不合适的上限。
我怀疑你想要(Java 8 之前的版本):
List<String> keyNameList = new ArrayList();
Element keystore = document.getRootElement();
for (Element element : keystore.getChildren("key")) {
keyNameList.add(element.getAttribute("name").getValue());
}
(您应该声明您的方法也返回 List<String>
。)
如果您还不熟悉泛型,我强烈建议您立即阅读它们。它们是现代 Java 编程的非常重要的一部分。
关于java - JDOM : cannot find symbol getAttribute(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35219420/