Re: JSP XML with DOM
designbyjohn@gmail.com wrote:
I am new to JSP and DOM, I am trying to get a subset of values
(categories) from an xml file which looks something like this:
<page>
<something>
...
</something>
<categories>
<category>cat1</category>
<category>cat2</category>
</categories>
</page>
So far I have come up with this. It returns "null null null", which is
interesting because there are only two categories in my xml file.. Any
help would be greatly appreciated.
Document doc = db.parse(file);
NodeList list = doc.getElementsByTagName("categories");
for (int i=0; i<list.getLength(); i++) {
Element element = (Element)list.item(i);
NodeList childNodes = element.getChildNodes();
if (childNodes != null) {
for (int x=0; x<childNodes.getLength(); x++) {
String string = childNodes.item(x).getNodeValue();
out.println(string);
}
}
}
A direct modification of your code that works is:
<%@ page language="java" import="javax.xml.parsers.*,org.w3c.dom.*" %>
<%
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse("C:/cat.xml");
NodeList list = doc.getElementsByTagName("categories");
for(int i = 0; i < list.getLength(); i++) {
Element element = (Element)list.item(i);
NodeList childNodes = element.getChildNodes();
for(int j = 0; j < childNodes.getLength(); j++) {
if(childNodes.item(j).getNodeType() == Node.ELEMENT_NODE &&
childNodes.item(j).getNodeName().equals("category")) {
Element child = (Element)childNodes.item(j);
String txt = child.getFirstChild().getNodeValue();
out.println(txt);
}
}
}
%>
But that code can be a lot simplified by using XPath:
<%@ page language="java"
import="javax.xml.parsers.*,org.w3c.dom.*,org.apache.xpath.*" %>
<%
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse("C:/cat.xml");
NodeList cats = XPathAPI.selectNodeList(doc,
"//page/categories/category/text()");
for(int i = 0; i < cats.getLength(); i++) {
String txt = cats.item(i).getNodeValue();
out.println(txt);
}
%>
And since JSTL supports XML, then it can done without scriptlet
code at all:
<%@ page language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/xml" prefix="x" %>
<c:import var="xml" url="file:///C:/cat.xml"/>
<x:parse var="doc" xml="${xml}"/>
<x:forEach select="$doc//page/categories/category">
<x:out select="."/>
</x:forEach>
Arne