XML : How to access child nodes by name in XML using DOM parser?

I have an xml file in following format:

  ....  <ecs:Person>       <ecs:abc>1234</ecs:abc>       <ecs:def>9090</ecs:def>  </ecs:Person>  <ecs:Person>       <ecs:def>1010</ecs:def>  </ecs:Person>  ...    

From above xml, we can understand that node "ecs:abc" is optional. I want to get value of "ecs:def" for all person. For that I was thinking to follow below approach:

  ....  int len = d.getElementsByTagName("ecs:Person").getLength();  for(int i=0;i < personLen;i++){      print d.getElementsByTagName("ecs:Person").item(j).getChildNodes().item(1).getTextContent()  }    

But as you can see, for second person node..as "ecs:abc" is not present so "ecs:def" will be at 0th position. So is there any way by which I can get the child nodes by Name not by position for respective "ecs:Person" node?

No comments:

Post a Comment