开发者

how to iterate through Xml using dom4j

my xml file:

<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>

Client :

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

My Test Class:

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

if i call getmachineByName(xyz) , i should get all the cred-pairs in a arraylist. I am confused in iteration.


The best way is probably with XPATH, with something like this. I'm assuming that you are using 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");
    ...
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜