0

Can someone tell me how to read this kind of XML file to get the child element names?

 <CEB>
    <MOREVALUES></MOREVALUES>
 </CEB>

 <DILOG>
    <MOREVALUES></MOREVALUES>
 </DILOG>

 <MOBITLE>
    <MOREVALUES></MOREVALUES>
 </MOBITLE>     

e.g I want to read all the child tags inside the <CTLBILL> tag. <CEB>, <DILOG>, and <MOBITLE> in this case.

This doesn't work:

public static void getTags() {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(new File("C:\\ctlbill.xml"));
            NodeList nodeLst = doc.getChildNodes();
            for (int s = 0; s < nodeLst.getLength(); s++)
            {           
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
}
3
  • 1
    Good formatting is your friend Aruna.. Commented May 26, 2011 at 5:32
  • Thanks Sener Gonul... Thanks for the help ... Commented May 26, 2011 at 5:35
  • what exactly doesn't work? nodeLst is empty, or nodeLst.item(i) returns not what you expect? Commented May 26, 2011 at 5:37

1 Answer 1

1

Try to use:

NodeList nodeLst = doc.getDocumentElement().getChildNodes();
for (int s = 0; s < nodeLst.getLength(); s++)
    if (nodeLst.item(s) instanceof Element)
        System.out.println(nodeLst.item(s).getNodeName());

I am assuming that CTLBILL is your document (root) element that contains CEB, DILOG and MOBITLE elements (well formed XML must have only one root element).

Sign up to request clarification or add additional context in comments.

1 Comment

Thsnks for the help buddy... :) NodeList nodeLst = doc.getDocumentElement().getChildNodes(); This is what I was missing.. Thanks a lot..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.