dom xml parser java, same tags

2.6k views Asked by At

i have this xml document which has varying number of same named tags. how can i get the count of the child elements and the value of it.

    <Question>
                <QuestionText>ABC?</QuestionText>
                <Option>A1 - XYZ</Option>
                <Option>A2 - WXY</Option>
                <Option>A2 - HJK</Option>
                <ID>1</ID>
            </Question>
    <Question>
   <QuestionText>ERY?</QuestionText>
<QuestionText>NNN?</QuestionText>
<QuestionText>KKKK?</QuestionText>
<ID>2</ID>
            </Question>

The output should read...

ID:2 Has 1 QuestionText and 3 Option QuestionText 1:ABC? Option 1:A1 - XYZ Option 2:A2 - WXY Option 3:A2 - HJK

ID:1 Has 3 QuestionText and 0 option QuestionText 1.ERY? QuestionText 2.NNN? QuestionText 3.KKKK?

I tried, but this gives fault results

    Element eElement = (Element) nNode;


      for(int i=0;i<eElement.getChildNodes().getLength();i++){
System.out.println("NodeName:"+eElement.getNodeName());
System.out.println("Tag value:"+getTagValue("QuestionText",eElement));
System.out.println("Tag value:"+getTagValue("Option",eElement));
    }

private static String getTagValue(String sTag, Element eElement){
    NodeList nlList= eElement.getElementsByTagName(sTag).item(0).getChildNodes();
    Node nValue = (Node) nlList.item(0); 

    return nValue.getNodeValue();    
}

After doing some research I found the solution

        Element eElement = (Element) nNode;

 getTagValue("QuestionText",eElement);
getTagValue("Option",eElement);

    private static void getTagValue(String sTag, Element eElement){
            NodeList nlList = eElement.getElementsByTagName(sTag);
            System.out.println("Size of nodelist:"+nlList.getLength());
            for(int i=0;i<nlList.getLength();i++){
                NodeList kList= eElement.getElementsByTagName(sTag).item(i).getChildNodes();
                Node kValue = (Node) kList.item(0); 
                System.out.println("Node Value:"+kValue.getNodeValue());
            }

        }
1

There are 1 answers

2
AudioBubble On BEST ANSWER

What is the getTagValue() ?

Anyway, it is the best tutorial (How to read XML file in Java) for DOM parser in java for me. Have a look at this

Here is getTagValue() from that link

private static String getTagValue(String sTag, Element eElement){
    NodeList nlList= eElement.getElementsByTagName(sTag).item(0).getChildNodes();
    Node nValue = (Node) nlList.item(0); 

    return nValue.getNodeValue();    
}