Presents your
XML E-NEWSLETTER for March 26, 2003
<------------------------------------------->
POPULATE WEB FORMS WITH JSP AND XML
We have shown you how to populate both C# forms and ASP.NET forms with
XML data. This tip will show you a similar technique for the Java platform.
You'll learn how to populate JavaServer Pages (JSPs) with XML data.
THE SAMPLE XML FILES
LISTING A and LISTING B show two sample XML documents that contain basic
information. You should place these documents in a directory called
C:\xmldocs, which we'll reference in our code:
Listing A: sample1.xml
\n");
}
%>
This relatively simple JSP displays a list of files. Each file is a link
to the ShowFile.jsp page, which we'll use to display the contents of the
XML file in an HTML form.
DISPLAYING THE XML DATA
In order to display the XML data in the HTML form, we'll need to parse
the XML document. We'll use the filename selected in the SelectFile.jsp
page to determine which document to parse. Then, we'll create a new
Document object based on the underlying physical XML document. We'll use the
new Document to locate specific values within the XML and show them within
the HTML form. This process is shown in LISTING D:
Listing D: ShowFile.jsp
<%@ page import="javax.xml.parsers.*,org.w3c.dom.*" %>
<%!
Document doc;
String getXMLValue(String name) {
.....//Node nodeName = DOMUtils.getChild(nodeRoot, name);
.....//String value = (nodeName == null) ? null :
DOMUtils.getTextValue(nodeName);
.....
.....NodeList nlist=doc.getElementsByTagName(name);
.....String value = nlist.item(0).getFirstChild().getNodeValue();
.....return value;
}
%>
<%
String xmlfile = "C:\\xmldocs\\" + request.getParameter("filename");
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
DocumentBuilder db=dbf.newDocumentBuilder();
doc=db.parse(xmlfile);
String name = getXMLValue("Name");
String address = getXMLValue("Address");
String city = getXMLValue("City");
String zip = getXMLValue("Zip");
String phone = getXMLValue("Phone");
%>
| Name: | |
| Address: | |
| City: | |
| Zip: | |
| Phone: |