user1652549
user1652549

Reputation: 65

How to read XML child node values of specific element?

I am trying to read child node value with attribute value of a specific element using DOM parser.. My xml file:

    <?xml version="1.0" encoding="UTF-8"?>
<RootNode>
    <SubNode Sid="1">
        <title>some text</title>
        <data dId="1">some text</data>
        <data dId="2">some text</data>
        <ExData>1</ExData>
    </SubNode>
    <SubNode Sid="2">
        <title>some text</title>
        <data dId="1">some text</data>
        <data dId="2">some text</data>
        <data dId="3">some text</data>
        <data dId="4">some text</data>
        <data dId="5">some text</data>
        <ExData>1</ExData>
    </SubNode>
    <SubNode Sid="3">
        <title>some text</title>
        <data dId="1">some text</data>
        <data dId="2">some text</data>
        <data dId="3">some text</data>
        <ExData>1</ExData>
    </SubNode>
</RootNode>

i am trying to read data nodes value of a one SubNode. i have checked with below code:

private void parseDocument()
{
    Element docEle = dom.getDocumentElement();
    NodeList nl = docEle.getElementsByTagName("SubNode");
    if(nl!= null && nl.getLength()>0)
    {
        for(int i=0; i<nl.getLength();i++)
        {
            Element el = (Element)nl.item(i);
            InfoBean que = getInfoBean(el);
            InfoBeanSet.add(que);
        }
    }
}
private InfoBean getInfoBean(Element el)
{
    int sId = Integer.parseInt(el.getAttribute("Sid"));
    String title = getTextValue(el,"title");    

    NodeList SingleOptionNode = el.getElementsByTagName("data");
    int nodeLen = SingleOptionNode.getLength();
    if(SingleOptionNode != null && nodeLen>0)
    {
        for(int i=0; i<nodeLen; i++)
        {
            Element el1 = (Element)SingleOptionNode.item(i);
            NodeList nextOption = el1.getChildNodes();
            Node currentNode = (Node) nextOption.item(0);
            int dId = Integer.parseInt(el1.getAttribute("dId"));
            String data = currentNode.getNodeValue();
            opt.add(new Option(data, dId));
        }
    }
    String ExData = getTextValue(el,"ExData");
    InfoBean ifb = new InfoBean(sId,title,opt,ExData);
    return ifb;
}

it gives data node values of all 3 SubNodes. how to read one SubNode element child node values with attribute value. Can i know the reason why am getting all data node value? can i get some code examples how to read data node value of a one SubNode element.. Any help would appreciated.

Upvotes: 0

Views: 12052

Answers (1)

Paul Butcher
Paul Butcher

Reputation: 6956

This line introduces a loop over all of the SubNode elements in your node list.

   for(int i=0; i<nl.getLength();i++)

Try not doing that.

Upvotes: 1

Related Questions