我是servlet编程的新手。我需要使用一个从客户端读取xml文件。我怎么能这样做?
有人可以向我推荐一些示例代码吗?我能够使用jaxb解析xml,但是如何从客户端获取xml本身呢?
答案 0 :(得分:3)
HERE您可以找到示例代码,请参见下文。
import java.io.*;
import org.w3c.dom.*;
import javax.servlet.*;
import javax.xml.parsers.*;
import javax.servlet.http.*;
public class ReadXML extends HttpServlet{
public boolean isTextNode(Node n){
return n.getNodeName().equals("#text");
}
public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try{
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse("C:/roseindia.xml");
out.println("<table border=2><tr><th>Name</th><th>Address</th></tr>");
Element element = doc.getDocumentElement();
NodeList personNodes = element.getChildNodes();
for (int i=0; i<personNodes.getLength(); i++){
Node emp = personNodes.item(i);
if (isTextNode(emp))
continue;
NodeList NameDOBCity = emp.getChildNodes();
out.println("<tr>");
for (int j=0; j<NameDOBCity.getLength(); j++ ){
Node node = NameDOBCity.item(j);
if ( isTextNode(node))
continue;
out.println("<td>"+(node.getFirstChild().getNodeValue())+"</td>");
}
out.println("</tr>");
}
out.println("</table>");
}
catch(Exception e){
System.out.println(e);
}
}
}
答案 1 :(得分:-1)
学会使用Google这样的搜索引擎,他们在大多数基本内容上都有很多方便的教程,而不是那么基本的东西
exmpale:
http://www.tutorialspoint.com/servlets/servlets-file-uploading.htm