java 如何使用 servlet 读取 xml 文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11789563/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I read xml file with a servlet?
提问by BKK
I am new to servlet programming. I need to read a xml file from a client using one. How can I do this?
我是 servlet 编程的新手。我需要使用一个从客户端读取 xml 文件。我怎样才能做到这一点?
Can anyone refer me to some example code? I'm able to parse xml using jaxb, but how can I get the xml itself from the client?
谁能给我推荐一些示例代码?我可以使用 jaxb 解析 xml,但是如何从客户端获取 xml 本身?
回答by Ahsan Khurshid
HEREyou can find an example code, See below also.
在这里您可以找到示例代码,另请参见下文。
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);
}
}
}
回答by Peter
learn to use search engines like google they have lots of handy tutorials on most of the basic and not so basic stuff
学习使用像谷歌这样的搜索引擎他们有很多关于大多数基本和不那么基本的东西的方便的教程
exmpale:
例子:
http://www.tutorialspoint.com/servlets/servlets-file-uploading.htm
http://www.tutorialspoint.com/servlets/servlets-file-uploading.htm