怎么在jsp页面中拼写XML

怎么在jsp页面中拼写XML,第1张

jsp中读取xml文件中内容的方法,案例如下:

1、XML文件

<?xml version="1.0" encoding="GB2312" ?> 

<!-- 个人履历表--> 

<resume>

<person id="01">

   <name>张三</name> 

   <birthday>03/24/1975</birthday>  

   <phone>1111-1111</phone> 

   <address>大连</address>

</person>  

<person id="02">

   <name>李四</name> 

   <birthday>9/26/1978</birthday>  

   <phone>2222-2222</phone> 

   <address>南京</address>

</person>   

<person id="03">

   <name>王五</name> 

   <birthday>11/09/1979</birthday>  

   <phone>3333-3333</phone> 

   <address>武汉</address>

</person>   

<person id="04">

   <name>赵六</name> 

   <birthday>6/04/1973</birthday>  

   <phone>4444-4444</phone> 

   <address>青岛</address>

</person>   

<person id="05">

   <name>陈七</name> 

   <birthday>12/19/1977</birthday>  

   <phone>5555-5555</phone> 

   <address>上海</address>

</person>   

</resume>

2、MyDOMBean.java

package test

import org.xml.sax.* 

import javax.xml.parsers.*

import org.w3c.dom.*

import java.io.*

 

public class MyDOMBean implements java.io.Serializable ...{

   private static String xmlStr=""

   private static final String PATH="file:///"

   public MyDOMBean() ...{

   }

 

   public String getString()...{

        return xmlStr

   }

 

   public static Document getDocument(String filename) throws Exception ...{

       xmlStr=""

       DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance()

        // 设定解析的叁数

        dbf.setIgnoringComments(true)

        dbf.setIgnoringElementContentWhitespace(true)

        DocumentBuilder db = dbf.newDocumentBuilder()

        //导入XML文件

        Document doc = db.parse(PATH+filename)

        

       return doc

   }

 

     public void traverseTree(Node node) throws Exception ...{

         if(node == null) ...{

            return

         }

         int type = node.getNodeType()

 

         switch (type) ...{

            //  *** 作DOCUMENT对象节点

            case Node.DOCUMENT_NODE: ...{

               xmlStr+="<tr>"

               traverseTree(((Document)node).getDocumentElement())

               break

            }

            //  *** 作XML元素节点

            case Node.ELEMENT_NODE: ...{

               String elementName = node.getNodeName()

               if(elementName.equals("person")) ...{

                 xmlStr+="</tr><tr>"

               }

               NodeList childNodes =node.getChildNodes()

               if(childNodes != null) ...{

                  int length = childNodes.getLength()

                  for (int loopIndex = 0 loopIndex <

                  length  loopIndex++)

                  ...{

                     traverseTree(childNodes.item(loopIndex))

                  }

               }

               break

            }

            //  *** 作XML文本节点

            case Node.TEXT_NODE: ...{

               String data = node.getNodeValue().trim()

               if((data.indexOf(" ")  <0) && (data.length()> 0)) ...{

                 xmlStr+="<td>"+data+"</td>"

               }

            }

         }

    }

 

}

3、jsp文件

<html>

<head>

<title>使用DOM解析器</title>

</head>

<%...@ page import="org.w3c.dom.*"%>

<%...@ page contentType="text/htmlcharset=GB2312" %>

<body bgcolor="#CFF1E1">

<center>

<h2>个人履历表(DOM版)</h2>

<table border="1" width="80%">

<tr>

<td>姓名</td>

<td>出生年月</td>

<td>电话号码</td>

<td>居住地</td>

</tr>

<jsp:useBean id="domparser" class="test.MyDOMBean" />

<%...  

   Document doc = domparser.getDocument(request.getRealPath("/") + "08_02.xml")

   domparser.traverseTree(doc)

   out.print(domparser.getString())

%>

</body>

</html>

1, jsp 解析xml

java解析xml有三种方式

1)dom,jdk自带,树形结构,缺点:一次性将xml文件加载到内存中,xml文件过大,效率很低

2)Dom4j.jar:第三方工具包(需导包),java中使用

3)sax:实现复杂,解决Dom文件过大问题,不是一次性加载,基于事件驱动模式解析

2,JSP *** 作XML

JSP读写XML文件

<%@ page contentType="text/htmlcharset=utf-8" %>

<%@ page import = "java.io.*,java.util.*,com.hexun.wap.zgpack.*,org.jdom.*,org.jdom.input.*,org.jdom.output.*" %>

<html>

<head>

<title>Basic News Page</title>

<style type="text/css"><!--td {font-size:12px}--></style>

</head>

<body>

<%

String t = request.getParameter("t")!=null?request.getParameter("t"):""

String s = request.getParameter("s")!=null?request.getParameter("s"):""

String d = request.getParameter("detail")!=null?request.getParameter("detail"):""

String delete = request.getParameter("delete")!=null?request.getParameter("delete"):""

String id = request.getParameter("id")!=null?request.getParameter("id"):""

SAXBuilder sb = new SAXBuilder()

String indent = " "

boolean newLines = true

XMLOutputter outp = new XMLOutputter (indent,newLines,"gb2312")

String flag = request.getParameter("flag")!=null?request.getParameter("flag"):"false"

if(flag.equals("true"))

{

byte[] b = t.getBytes("iso8859-1")

String ti = new String(b,"utf-8")

byte[] b2 = s.getBytes("iso8859-1")

String si = new String(b2,"utf-8")

byte[] b3 = d.getBytes("iso8859-1")

String di = new String(b3,"utf-8")

try

{

Document doc=sb.build(new FileInputStream("/usr/local/stockdata/basic.xml"))

Element root=doc.getRootElement()

List list=root.getChildren()

Element article = new Element("message")

article.setAttribute("id",(list.size()+10001)+"")

article.addContent(new Element("title").setText(ti))

article.addContent(new Element("content").setText(di))

article.addContent(new Element("time").setText(si))

doc.getRootElement().addContent(article)

outp.output(doc,new FileOutputStream("/usr/local/stockdata/basic.xml"))

}

catch(Exception e)

{

e.printStackTrace()

}

s = ""

d = ""

t = ""

}

if(delete.equals("true"))

{

new XMLFile().removeContent("/usr/local/stockdata/basic.xml",Integer.parseInt(id))

}

%>

<form action="OperBasic.jsp" method="post">

<table width=80% border=0 bgcolor=#FFE4C4 cellspacing=1 cellpadding=1 align=center>

<tr><td colspan=2>Add Basic News :</td></tr>

<tr>

<td>Title:</td><td><input type="text" name="t" value="<%=t%>" maxlength="60" format="*N" style="border-width:1border-color:blackborder-style:solid"/></td></tr>

<tr><td>Time/Author:</td><td><input type="text" name="s" value="<%=s%>" maxlength="20" format="*N" style="border-width:1border-color:blackborder-style:solid"/></td></tr>

<tr><td>Content:</td><td><textarea name="detail" rows="10" cols="66" style="border-width:1border-color:blackborder-style:solid"></textarea><br/>

</td>

<tr><td colspan=2 align=center><input type="submit" name="submit" value="Add"/></td>

<input type="hidden" name="flag" value="true" maxlength="20" format="*N"/>

</tr>

</table>

</form>

<table width=80% border=0 bgcolor=000000 cellspacing=1 cellpadding=1 align=center><tr><td bgcolor=FF7Dff>ID</td><td bgcolor=FF7Dff>Title</td><td bgcolor=FF7Dff>Content</td><td bgcolor=FF7Dff>Time / Author</td><td bgcolor=FF7Dff>Delete</td></tr>

<%

try

{

Document doc = sb.build(new FileInputStream("/usr/local/stockdata/basic.xml"))

Element root = doc.getRootElement()

List list = root.getChildren()

out.println("all:"+list.size())

for(int i=0i<list.size()i++)

{

Element item = (Element)list.get(i)

String name = item.getAttribute("id").getValue()

out.println("<tr><td width=5% height=30 align=left bgcolor=FF7D00>"+name+"</td>")

Element sub = item.getChild("title")

String text = sub.getText()

out.println("<td width=10% height=30 align=left bgcolor=FF7D00>"+ text+"</td>")

Element sub2 = item.getChild("content")

String text2 = sub2.getText()

out.println("<td width=50% align=left bgcolor=FF7D00>"+ text2+"</td>")

Element sub3 = item.getChild("time")

String text3 = sub3.getText()

out.println("<td width=10% align=left bgcolor=FF7D00>"+ text3+ "</td>")

out.println("<td width=5% align=left bgcolor=FF7D00><a href=OperBasic.jsp?delete=true&id="+ i +" onclick=/"{if(confirm("+"'are you sure?'"+")){return true}return false}/">Delete</a></td>")

//out.println("<td width=5% align=left bgcolor=FF7D00><a href=OperBasic.jsp?delete=true&id="+ i + ">Delete</a></td>")

out.println("</tr>")

}

}

catch(Exception e)

{

e.printStackTrace()

}

%>

</table>

<br/>

</body>

</html>


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/tougao/11449170.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-16
下一篇 2023-05-16

发表评论

登录后才能评论

评论列表(0条)

保存