0

我的 xml 文件:

<credentials>
 <machine name="xyz">
  <cred-pairs>
   <cred-pair>
    <login>asad</login>
    <password>12345</password>
   </cred-pair>
 <cred-pair>
    <login>ggss</login>
    <password>97653</password>
   </cred-pair>
   <cred-pairs>
 </machine>
 <machine name="pqr">
  <cred-pair>
   <cred-pair>
    <login>ssdas</login>
    <password>12345</password>
   </cred-pair>
   <cred-pairs>
 </machine>
</credentials>

客户 :

public Client
{
String login;
String password;
//getters
Client(String login,String password)
{
this.login=login;
this.password=password;
}
}

我的测试班:

Class Test{
getMachineByName(String machineName)
{
ArrayList<Client> machineClients=new ArrayList<Client>();
/*here i have to iterate through xml and upon machineName i have to create Client objects using cred-pair(s) in cred-pairs node and add to machineClientsList 
}
}

如果我打电话getmachineByName(xyz),我应该得到一个数组列表中的所有信用对。我在迭代中感到困惑。

4

1 回答 1

0

最好的方法可能是使用 XPATH,像这样。我假设您使用的是 Dom4j 1.6.1。

Document document = DocumentHelper.parseText(xmlFileAsString);

List<Element> elements = document.getRootElement()
    .selectNodes("//machine[@name='"+machineName+"']//cred-pair");

for (Element element : elements) {
    String login = element.attributeValue("login");
    String pwd = element.attributeValue("password");
    ...
}
于 2011-08-26T16:50:03.103 回答