Reputation: 4815
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?
Upvotes: 1
Views: 5080
Reputation: 3079
1 look for getElementsByTagName("ecs:Person")
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
NodeList nList = d.getElementsByTagName("ecs:Person");
for (int temp = 0; temp < nList.getLength(); temp++)
{
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE)
{
Element eElement = (Element) nNode;
Dont use index 0, 1 , ...
2 inside each one, look for getElementsByTagName("ecs:def")
// DO IT AGAIN:
eElement.getElementsByTagName("ecs:def");
Upvotes: 2