How to parse xml file
Hi,
I am having an XML file which is having set of repeated tags like
<gender>
<male>
<name>sk</name>
<age>19</age>
</male>
<male>
<name>raj</name>
<age>20</age>
</male>
<male>
<name>kris</name>
<age>18</age>
</male>
</gender>
Like this i am having the xml file, i have to read the values from this xml file, here we are having male tag is repeated, from this i have to take the name, and age values. can you tell me how to take these values. If you are having the sample send me.
Thanks,
Hai
It may be a bit late to reply but i hope this code will help you
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.*;
import java.io.File;
import org.w3c.dom.*;
class DomParse
{
public void func()
{
try
{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
//File f =new File("trial.xml");
Document doc = db.parse(new File("trial.xml")); //your xml file name here
//Document doc = db.parse(f);
NodeList nl1 = doc.getElementsByTagName("male");
for(int i=0;i<nl1.getLength();i++)
{
Node nd = nl1.item(i);
NodeList tmplist = nd.getChildNodes();
for(int j=0;j<tmplist.getLength();j++)
{
Node tmpNode = tmplist.item(j);
String locStr = tmpNode.getTextContent();
System.out.println(""+tmpNode.getTextContent());
}
}
}
catch(Exception e)
{
System.out.println("Error: "+e);
e.printStackTrace();
}
}
public static void main(String[] args) //throws
{
new DomParse().func();
}
}
with regards
shan>