这里,我试图将xml文件值获取到Java List,然后在表中显示这些值。通过使用DOM解析器,我可以从XML文件中获取XML值。我想将此输出返回到JSP表。请帮助我完成此操作!
1)XML阅读器。。>
public class ReadXMLFile { public static void main(String argv[]) { try { File fXmlFile = new File("/Users/mkyong/staff.xml"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(fXmlFile); //optional, but recommended //read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work doc.getDocumentElement().normalize(); System.out.println("Root element :" + doc.getDocumentElement().getNodeName()); NodeList nList = doc.getElementsByTagName("staff"); System.out.println("----------------------------"); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); System.out.println("\nCurrent Element :" + nNode.getNodeName()); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; System.out.println("Staff id : " + eElement.getAttribute("id")); System.out.println("First Name : " + eElement.getElementsByTagName("firstname").item(0).getTextContent()); System.out.println("Last Name : " + eElement.getElementsByTagName("lastname").item(0).getTextContent()); System.out.println("Nick Name : " + eElement.getElementsByTagName("nickname").item(0).getTextContent()); System.out.println("Salary : " + eElement.getElementsByTagName("salary").item(0).getTextContent()); } } } catch (Exception e) { e.printStackTrace(); } }}
2)JSp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page import="xmlReader.TestXmlReader"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>XML Viewer</title>
</head>
<body>
<% TestXmlReader tc = new TestXmlReader();
NodeList LiNew = TestXmlReader;%>
<p><%=LiNew %></p> //need to add in to table just for testing
</body>
</html>
这里,我试图将xml文件值获取到Java List,然后在表中显示这些值。通过使用DOM解析器,我可以从XML文件中获取XML值。我想将此输出返回给JSP ...
无法通过这种方式工作。您需要创建一个Servlet程序,在其中必须填充List
。在Servlet代码内部,您必须将列表放入请求对象,然后将请求转发到JSP。然后,您可以使用scriptlet在JSP中检索列表,然后以核心Java方式或使用JSTL(推荐)库对其进行迭代。下面给出了一些您可以从以下链接开始的链接: