So I have my documentbuilder and I'm doing this the DOM way. I've managed to get to the point where I have saved the tag I want into a nodelist

NodeList list = doc.getElementsByTagName("myTag");

the xml looks like this
<myTag id="1"/>

but now I want to grab the id number and I can't figure out how to specify which parameter I want to grab. How is this typically done?

but lets say I dont know the index of the element. So what if the tag looks like...

<myTag someParameter="cheese" stuff="things" id="1"/>
or
<myTag someParameter="cheese" id="1" stuff="things"/>

So lets say I have a case where I don't know the order of the parameters? So id="1" could be anywhere in the tag for all I know.

Edited 6 Years Ago by RichardCrickets: n/a

your "list" (NodeList) contains all the xml elements. You first need to iterate through its elements. Each element is a Java "Element". With that element you can get the attribute. It doesnt care what order they are in. Look at the Java API for NodeList.

the code seem to be like this :

// iterate through element
        for (int i = 0; i < children.getLength(); i++)
        {
			// get current child
            Node n = children.item(i);

            // we're only interested in Element children
            if (n.getNodeType() == Node.ELEMENT_NODE)
Element element=((Element) n);
            String attributeValue=element.getAttribute("id");            
        }

Where children is our NodeList .

Hope it helps.

Sorry!!

// iterate through element
        for (int i = 0; i < children.getLength(); i++)
        {
			// get current child
            Node n = children.item(i);

            // we're only interested in Element children
            if (n.getNodeType() == Node.ELEMENT_NODE){
Element element=((Element) n);
            String attributeValue=element.getAttribute("id");  
}          
        }
This article has been dead for over six months. Start a new discussion instead.