Element retrieve by tag name
In this chapter you will learn:
Get element by tag name
getElementsByTagName
accepts tag name as parameter and
return a NodeList
containing elements whose tag name is passed in parameter.
The following code gets tags by tag name employee.
NodeList nodes = doc.getElementsByTagName("employee");
The following code shows how to use getElementsByTagName
to get element by tag name.
import java.io.StringReader;
// j a v a2 s .co m
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
public class Main {
public static void main(String[] args) throws Exception {
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xmlRecords));
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(is);
NodeList nodes = doc.getElementsByTagName("employee");
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
}
}
static String xmlRecords =
"<data>" +
" <employee>" +
" <name>Tom</name>"+
" <title>Manager</title>" +
" </employee>" +
" <employee>" +
" <name>Jerry</name>"+
" <title>Programmer</title>" +
" </employee>" +
"</data>";
}
Next chapter...
What you will learn in the next chapter:
Home » Java Tutorial » XML