我正在尝试使用这段代码来解析放在外部服务器上的XML文件。问题是输出只列出表中的第一个结果。有什么建议为什么会这样?代码非常混乱,我为此道歉。我正在使用此代码作为学校实验来测试通过servlet进行解析,这基本上只是我在网上找到的预制servlet,我正在尝试适应我的项目。
如果有人能够解决我的问题,或想出一个更好的解决方案来解决问题,我将非常感激!
import java.io.*;
import org.w3c.dom.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.xml.parsers.*;
import javax.servlet.http.*;
@WebServlet(urlPatterns = {"/Veivesen"})
public class Veivesen 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("http://www.p4.no/rss/trafikk.aspx?area=20");
out.println("<table border=2><tr><th>Title</th><th>Link</th></tr>");
Element element = doc.getDocumentElement();
NodeList newsNodes = element.getChildNodes();
for (int i=0; i<newsNodes.getLength(); i++){
Node news = newsNodes.item(i);
out.println(news);
if (isTextNode(news))
continue;
NodeList NameDOBCity = news.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>");
System.out.println(node.getFirstChild());
}
out.println("</tr>");
}
out.println("</table>");
} catch(Exception e) {
System.out.println(e);
}
}
}
答案 0 :(得分:0)
如果你要做的是阅读RSS频道中的项目,你需要找到合适的xml元素,试试doGet
方法的这个修改版本:
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("http://www.p4.no/rss/trafikk.aspx?area=20");
out.println("<html><body><table border=2><tr><th>Title</th><th>Link</th></tr>");
Element element = doc.getDocumentElement();
NodeList channelNodes = element.getElementsByTagName("channel");
NodeList newsNodes = ((Element)channelNodes.item(0)).getElementsByTagName("item");
for (int i=0; i<newsNodes.getLength(); i++){
Node news = newsNodes.item(i);
//out.println(news);
if (isTextNode(news))
continue;
NodeList NameDOBCity = news.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>");
System.out.println(node.getFirstChild());
}
out.println("</tr>");
}
out.println("</table></body></html>");
} catch(Exception e) {
System.out.println(e);
}
}