??xml version="1.0" encoding="utf-8" standalone="yes"?>亚洲综合99,xxxxxhd亚洲人hd,成人国产在线视频http://www.aygfsteel.com/flustar/category/22096.html不是因ؓ有些事情难以做到Q我们才失去自信Q而是因ؓ我们失去了自信,有些事情才难以做到?/description>zh-cnTue, 20 Nov 2007 23:21:47 GMTTue, 20 Nov 2007 23:21:47 GMT60Zspring+dwr+xml无刷新投?调查)pȝhttp://www.aygfsteel.com/flustar/archive/2007/11/19/spring_dwr_xml.htmlflustarflustarMon, 19 Nov 2007 10:04:00 GMThttp://www.aygfsteel.com/flustar/archive/2007/11/19/spring_dwr_xml.htmlhttp://www.aygfsteel.com/flustar/comments/161691.htmlhttp://www.aygfsteel.com/flustar/archive/2007/11/19/spring_dwr_xml.html#Feedback0http://www.aygfsteel.com/flustar/comments/commentRss/161691.htmlhttp://www.aygfsteel.com/flustar/services/trackbacks/161691.html一、徏立xml的数据结构,文g名ؓQvote.xmlQ内容如下:

<?xml version="1.0" encoding="UTF-8"?>

<votes voteTotalCount="0">

    <vote voteId="1" name="c语言 " voteCount="0" percentum="0" />

    <vote voteId="2" name="c++" voteCount="0" percentum="0" />

    <vote voteId="3" name="java" voteCount="0" percentum="0" />

    <vote voteId="4" name="汇编语言" voteCount="0" percentum="0" />

 </votes>

在你的web应用的根目录建立xml文g夹,其拯到该目录下?/p>

二、徏立xml对应的bean

/**

 * @author flustar

 * @version 创徏旉QJul 11, 2007 5:17:53 PM

 * c说?/p>

 */

……………………………………………………………………….

……………………………………………………………………….

public class VoteBean {

    private String voteId;

   private String name;

    private String voteCount;

    private String voteTotalCount;

    private String percentum;

    public VoteBean() {

      

    }

    public String getPercentum() {

       return percentum;

    }

    public void setPercentum(String percentum) {

       this.percentum = percentum;

    }

    public String getVoteId() {

       return voteId;

    }

 

    public void setVoteId(String voteId) {

       this.voteId = voteId;

    }

    public String getName() {

       return name;

    }

    public void setName(String name) {

       this.name = name;

    }

    public String getVoteCount() {

       return voteCount;

    }

 

    public void setVoteCount(String voteCount) {

       this.voteCount = voteCount;

    }

}

三、徏立处理具体逻辑的service

package com.flustar.service;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.text.NumberFormat;

import java.util.ArrayList;

import java.util.Iterator;

import java.util.List;

import org.jdom.Attribute;

import org.jdom.Document;

import org.jdom.Element;

import org.jdom.input.SAXBuilder;

import org.jdom.output.Format;

import org.jdom.output.XMLOutputter;

import org.jdom.xpath.XPath;

import com.flustar.web.beans.VoteBean;

import com.flustar.web.config.ContextConfig;

public class VoteService {

       private Element root, vote;

       private Document doc;

      private Attribute voteTotalCount;

       private VoteBean voteBean;

       private List<VoteBean> voteBeanList;

       private String path = ContextConfig.getContextPath()

                     + "/xml/vote.xml";

       public void buildDoc() throws Exception {

              FileInputStream fi = null;

              fi = new FileInputStream(path);

              SAXBuilder sb = new SAXBuilder();

              doc = sb.build(fi);

       }

       public void formatDoc() throws Exception {

              Format format = Format.getCompactFormat();

              format.setEncoding("UTF-8");// 讄xml文g的字WؓUTF-8

              format.setIndent("    ");// 讄xml文g~进?个空?/p>

              XMLOutputter xmlOut = new XMLOutputter(format);

              xmlOut.output(doc, new FileOutputStream(path));

       }

 

       public String floatToPercentum(Double doubleNum) {

              NumberFormat numberFormat = NumberFormat.getPercentInstance();

              numberFormat.setMinimumFractionDigits(2);

              // numberFormat.setMaximumIntegerDigits(2);

              String str = numberFormat.format(doubleNum);

              //System.out.println(str);

              return str;

       }

 

       public void updateVoteCount(String voteId) throws Exception {

              buildDoc();

              root = doc.getRootElement();

              vote = (Element) XPath.selectSingleNode(root, "http://vote[@voteId='"

                            + voteId + "']");

              int voteCount = Integer.parseInt(vote.getAttributeValue("voteCount")) + 1;

              //System.out.println(voteCount);

              vote.setAttribute("voteCount", String.valueOf(voteCount));

              int totalCount = Integer.parseInt(root

                            .getAttributeValue("voteTotalCount")) + 1;

              voteTotalCount = new Attribute("voteTotalCount", String

                            .valueOf(totalCount));

              root.setAttribute(voteTotalCount);

              System.out.println(totalCount);

              formatDoc();

              updateAllVoteCount();//更新所有的癑ֈ?/p>

 

       }

    public void updateAllVoteCount()throws Exception{

           buildDoc();

           root=doc.getRootElement();

           int totalCount = Integer.parseInt(root

                            .getAttributeValue("voteTotalCount"));

           List voteList=XPath.selectNodes(root,"/votes/vote");

           for(int i=0;i<voteList.size();i++){

                  vote=(Element)voteList.get(i);

                  int voteCount = Integer.parseInt(vote.getAttributeValue("voteCount"));

                  System.out.println(voteCount);

                  vote.setAttribute("voteCount", String.valueOf(voteCount));

                  vote.setAttribute("percentum", floatToPercentum(1.0 * voteCount

                                / totalCount));

           }

           formatDoc();

    }

       public List getAllVote() throws Exception {

              buildDoc();

              voteBeanList = new ArrayList();

              root = doc.getRootElement();

              String totalCount = root.getAttributeValue("voteTotalCount");

              List voteList = root.getChildren();

              Iterator i = voteList.iterator();

 

              while (i.hasNext()) {

                     voteBean = new VoteBean();

                     voteBean.setVoteTotalCount(totalCount);

                     vote = (Element) i.next();

                     String name = vote.getAttributeValue("name");

                     String voteCount = vote.getAttributeValue("voteCount");

                     String percentum = vote.getAttributeValue("percentum");

 

                     voteBean.setName(name);

                     voteBean.setVoteCount(voteCount);

                     voteBean.setPercentum(percentum);

                     voteBeanList.add(voteBean);

              }

              return voteBeanList;

       }

 

}

 

    public String getVoteTotalCount() {

       return voteTotalCount;

    }

 

    public void setVoteTotalCount(String voteTotalCount) {

       this.voteTotalCount = voteTotalCount;

    }

}

 

四、获取上下文路径的listener

package com.flustar.web.listener;

import javax.servlet.ServletContextEvent;

import javax.servlet.ServletContextListener;

import com.flustar.web.config.ContextConfig;

public class ConfigLoadContextListener implements  ServletContextListener{

    public void contextDestroyed(ServletContextEvent arg0) {

       // TODO Auto-generated method stub

           }

    public void contextInitialized(ServletContextEvent contextEvent) {

       // TODO Auto-generated method stub

              String contextPath = contextEvent.getServletContext().getRealPath("/");

       ContextConfig.setContextPath(contextPath);

           }

}

………………………………………………………..

……………………………………………………………

 

public class ContextConfig {

    private static String contextPath;

 

    public static String getContextPath() {

       return contextPath;

    }

 

    public static void setContextPath(String contextPath) {

       ContextConfig.contextPath = contextPath;

    }

……………………………………………………………………

………………………………………………………………..

}

五、在applicationContext-service.xml中注册VoteService

<bean name="voteService" class="com.flustar.service.imp.VoteService"/>

六、注册xmlQ在你的web应用的WEB-INFO目录下徏立applicationContext-dwr.xml文gQ内容ؓQ?/p>

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 2.0//EN" "http://getahead.org/dwr/dwr20.dtd">

<dwr>

    <allow>

      <create  creator="spring" javascript="VoteService" >

         <param name="beanName" value="voteService"></param>

         <include method="updateVoteCount"/>

         <include method="getAllVote"/>

      </create>

      <convert converter="bean"  match="com.flustar.web.beans.VoteBean" />

           </allow>

</dwr>

 

七、修改web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://java.sun.com/xml/ns/j2ee"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"

    version="2.4">

    …………………………………………………………………………………………………………………………

………………………………………………………………………………………………………………………………..

    <context-param>

       <param-name>contextConfigLocation</param-name>

       <param-value>

…………………………………..

       /WEB-INF/classes/applicationContext-service.xml

</param-value>

    </context-param>

 …………………………………………………………………………………………………………………………………………….     <listener-class>com.flustar.web.listener.ConfigLoadContextListener</listener-class>

    …………………………………………………………………………………………………………………………………………….   

  <servlet>

    <servlet-name>dwr-invoker</servlet-name>

    <servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class>

    <init-param>

      <param-name>debug</param-name>

      <param-value>true</param-value>

    </init-param>

  </servlet>

 

  <servlet-mapping>

    <servlet-name>dwr-invoker</servlet-name>

    <url-pattern>/dwr/*</url-pattern>

  </servlet-mapping> 

…………………………………………………………………………………………………………………………………………….   

</web-app>

八、jsp面

1)

<%@ page contentType="text/html; charset=gbk" language="java" import="java.sql.*" errorPage="" %>

<html>

<head>

<title>投票pȝ</title>

       <script type='text/javascript' src='dwr/engine.js'> </script>

        <script type='text/javascript' src='dwr/util.js'> </script>

        <script type='text/javascript' src='dwr/interface/VoteService.js'> </script>

       <script type='text/javascript'>

function vote(){

       

     var   obj=document.getElementsByName('radio'); 

    

         if   (obj!=null){ 

         var j=0;

           for   (var   i=0;i<obj.length;i++){ 

             if   (obj[i].checked)  

              {  

               

                   VoteService.updateVoteCount(obj[i].value);

                   alert("投票成功!");

                  obj[i].checked=false;

                  break;

               }

              }

               j=j+1;

             

          }

         if(j==obj.length){

                alert("请选中其中的一,再投?");

               }

          

      }

   

    }

  function showwin(){

    window.open('voteresult.htm','voteresult','height=400, width=400, top=0, left=0, toolbar=no, menubar=no, scrollbars=no, resizable=no,location=no, status=no');

   }

 }

</script>

</head>

<body>

<div >

    <h1 >

       你用最多的一门语a是?

    </h1>

</div>

<div>

<div>

        <span>     <h1><input type="radio" name="radio" id="radio" value="1" />

       C语言</h1>

        </span>

       <span> <h1 ><input type="radio" name="radio" id="radio" value="2" />c++ </h1> </span>

       <span ><h1 ><input type="radio" name="radio" id="radio" value="3" />java </h1> </span>

       <span><h1 ><input type="radio" name="radio" id="radio" value="4"/>汇编语言</h1> </span>

</div>

</div>

<div id="toupiao"><input class="btn" type="button" value="投票" onClick="vote()" /><input class="btn" type="button" value="查看" onClick="showwin()"/></div>

</body>

</html>

2)

<html>

<head>

<meta http-equiv="content-type" content="text/html; charset=gb2312">

<title>投票l果</title>

       <script type='text/javascript' src='dwr/engine.js'> </script>

        <script type='text/javascript' src='dwr/util.js'> </script>

        <script type='text/javascript' src='dwr/interface/VoteService.js'> </script>

        <script type='text/javascript' >

function showresult(){

             VoteService.getAllVote(function(data){

             document.getElementById("totalCount").innerHTML=data[0].voteTotalCount;

             for(var i=0;i<data.length;i++){

                  var voteBean=data[i];

                  document.getElementById("xuanshou"+i).innerHTML=voteBean.name;

                  document.getElementById("baifenbi"+i).innerHTML=voteBean.percentum;

                  document.getElementById("piaoshu"+i).innerHTML=voteBean.voteCount;

                  document.getElementById("img"+i).width=voteBean.voteCount/data[0].voteTotalCount*310;

                                   

      }

    });

          

}

</script>

</head>

<body onLoad="showresult()">

<div id="voteRs">

<table border="0" cellpadding="0" cellspacing="0">

  <CAPTION valign="top" class="subject">

投票l果

    </CAPTION>

  <tbody>

  <tr >

    <th>语言</th>

    <th>癑ֈ?lt;/th>

    <th>数</th>

  </tr>

  <tr>

    <td><span id="xuanshou0"></span></td>

    <td><span id="baifenbi0"></span><img id="img0" src='images/voteprogress.gif' width=0 height=10></td>

    <td><span id="piaoshu0"></span></td>

  </tr>

  <tr>

    <td><span id="xuanshou1"></span></td>

    <td><span id="baifenbi1"></span><img id="img1" src='images/voteprogress.gif' width=0 height=10></td>

    <td><span id="piaoshu1"></span></td>

  </tr>

  <tr>

    <td><span id="xuanshou2"></span></td>

    <td><span id="baifenbi2"></span><img id="img2" src='images/voteprogress.gif' width=0 height=10></td>

    <td><span id="piaoshu2"></span></td>

  </tr>

   <tr>

    <td><span id="xuanshou3"></span></td>

    <td><span id="baifenbi3"></span><img id="img3" src='images/voteprogress.gif' width=0 height=10></td>

    <td><span id="piaoshu3"></span></td>

  </tr>

 

  </tbody>

</table>

?lt;span id="totalCount"></span>条投?lt;br/>

[<span onClick="javascript:window.close();">关闭H口</span>]

</div>

</body>

</html>

 



flustar 2007-11-19 18:04 发表评论
]]>
JDOM使用详解及实?/title><link>http://www.aygfsteel.com/flustar/archive/2007/04/29/114561.html</link><dc:creator>flustar</dc:creator><author>flustar</author><pubDate>Sun, 29 Apr 2007 06:08:00 GMT</pubDate><guid>http://www.aygfsteel.com/flustar/archive/2007/04/29/114561.html</guid><wfw:comment>http://www.aygfsteel.com/flustar/comments/114561.html</wfw:comment><comments>http://www.aygfsteel.com/flustar/archive/2007/04/29/114561.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.aygfsteel.com/flustar/comments/commentRss/114561.html</wfw:commentRss><trackback:ping>http://www.aygfsteel.com/flustar/services/trackbacks/114561.html</trackback:ping><description><![CDATA[<span style="color: #3e3838;" class="checkoutHeader"><strong>JDOM是一个开源项目,它基于树型结构,利用UJAVA的技术对XML文档实现解析、生成、序列化以及多种操作?/strong></span> <font style="color: #3e3838;" color="#009900"> </font> <div style="color: #3e3838;" id="content"> <p>一、JDOM ?/p> <p>JDOM是一个开源项目,它基于树型结构,利用UJAVA的技术对XML文档实现解析、生成、序列化以及多种操作?/p> <p>JDOM 直接为JAVA~程服务。它利用更ؓ强有力的JAVA语言的诸多特性(Ҏ(gu)重蝲、集合概念以及映)Q把SAX和DOM的功能有效地l合h?/p> <p>在用设计上可能地隐藏原来使用XMLq程中的复杂性。利用JDOM处理XML文档是一件轻松、简单的事?/p> <p>JDOM ?000q的春天被Brett McLaughlin和Jason Hunter开发出来,以I补DOM及SAX在实际应用当中的不之处?/p> <p>q些不之处主要在于SAX没有文档修改、随问以及输出的功能Q而对于DOM来说QJAVAE序员在使用时来用v来总觉得不太方ѝ?/p> <p>DOM的缺点主要是来自于由于Dom是一个接口定义语aQIDLQ?它的d是在不同语言实现中的一 个最低的通用标准Qƈ不是为JAVA特别设计的。JDOM的最新版本ؓJDOM Beta 9。最qJDOM被收录到JSR-102内,q标志着JDOM成ؓ了JAVAq_l成的一部分?/p> <p>二、JDOM 包概?/p> <p>JDOM是由以下几个包组成的<br>org.jdom                包含了所有的xml文档要素的javac?/p> <p> </p> <p>org.jdom.adapters         包含了与dom适配的javac?/p> <p> </p> <p>org.jdom.filter            包含了xml文档的过滤器c?/p> <p> </p> <p>org.jdom.input            包含了读取xml文档的类</p> <p> </p> <p>org.jdom.output           包含了写入xml文档的类</p> <p> </p> <p>org.jdom.transform        包含了将jdom xml文档接口转换为其他xml文档接口</p> <p> </p> <p>org.jdom.xpath            包含了对xml文档xpath操作的类三、JDOM c说?/p> <p>1、org.JDOMq个包里的类是你J解析xml文g后所要用到的所有数据类型?/p> <p>Attribute</p> <p>CDATA</p> <p>Coment</p> <p>DocType</p> <p>Document</p> <p>Element</p> <p>EntityRef</p> <p>Namespace</p> <p>ProscessingInstruction</p> <p>Text</p> <p>2、org.JDOM.transform在涉及xslt格式转换时应使用下面?个类</p> <p>JDOMSource</p> <p>JDOMResult</p> <p>org.JDOM.input</p> <p>3、输入类Q一般用于文档的创徏工作</p> <p>SAXBuilder</p> <p>DOMBuilder</p> <p>ResultSetBuilder</p> <p>org.JDOM.output</p> <p>4、输出类Q用于文档{换输?/p> <p>XMLOutputter</p> <p>SAXOutputter</p> <p>DomOutputter</p> <p>JTreeOutputter</p> <p>使用前注意事:</p> <p>1.JDOM对于JAXP 以及 TRax 的支?/p> <p>JDOM 支持JAXP1.1Q你可以在程序中使用M的parser工具c?默认情况下是JAXP的parser?/p> <p>制定特别的parser可用如下形式</p> <p>SAXBuilder parser </p> <p>  = new SAXBuilder("org.apache.crimson.parser.XMLReaderImpl");</p> <p> Document doc = parser.build("http://www.cafeconleche.org/");</p> <p> // work with the document...</p> <p>JDOM也支持TRaXQXSLT可通过JDOMSource以及JDOMResultcL转换Q参见以后章节)</p> <p>2.注意在JDOM里文档(DocumentQ类由org.JDOM.Document 来表C。这要与org.w3c.dom中的Document区别开Q这2U格式如何{换在后面会说明?/p> <p>以下如无Ҏ(gu)均指JDOM里的Document?/p> <p>四、JDOM主要使用Ҏ(gu)</p> <p>1.Ducumentc?/p> <p>(1)Document的操作方法:</p> <p>Element root = new Element("GREETING");</p> <p>Document doc = new Document(root);</p> <p>root.setText("Hello JDOM!");</p> <p>或者简单的使用Document doc = new Document(new Element("GREETING").setText("Hello JDOM!t"));</p> <p>q点和DOM不同。Dom则需要更为复杂的代码Q如下:</p> <p>DocumentBuilderFactory factory =DocumentBuilderFactory.newInstance();</p> <p>DocumentBuilder builder =factory.newDocumentBuilder();</p> <p>Document doc = builder.newDocument();</p> <p>Element root =doc.createElement("root");</p> <p>Text text = doc.createText("This is the root");</p> <p>root.appendChild(text);</p> <p>doc.appendChild(root);</p> <p>注意事项QJDOM不允许同一个节点同时被2个或多个文档相关联,要在W?个文档中使用原来老文档中的节点的话。首先需要用detach()把这个节点分开来?/p> <p>(2)从文件、流、系lID、URL得到Document对象Q?/p> <p>DOMBuilder builder = new DOMBuilder();</p> <p>Document doc = builder.build(new File("jdom_test.xml"));</p> <p>SAXBuilder builder = new SAXBuilder();</p> <p>Document doc = builder.build(url);</p> <p>在新版本中DOMBuilder 已经Deprecated?DOMBuilder.builder(url)Q用SAX效率会比较快?/p> <p>q里举一个小例子Qؓ了简单v见,使用String对象直接作ؓxml数据源:</p> <p> public jdomTest() {</p> <p>    String textXml = null;</p> <p>    textXml = "<note>";</p> <p>    textXml = textXml +</p> <p>        "<to>aaa</to><from>bbb</from><heading>ccc</heading><body>ddd</body>";</p> <p>    textXml = textXml + "</note>";</p> <p>    SAXBuilder builder = new SAXBuilder();</p> <p>    Document doc = null;</p> <p>    Reader in= new StringReader(textXml);</p> <p>    try {</p> <p>      doc = builder.build(in);</p> <p>      Element root = doc.getRootElement();</p> <p>      List ls = root.getChildren();//注意此处取出的是root节点下面的一层的Element集合</p> <p>      for (Iterator iter = ls.iterator(); iter.hasNext(); ) {</p> <p>        Element el = (Element) iter.next();</p> <p>        if(el.getName().equals("to")){</p> <p>         System.out.println(el.getText());</p> <p>        }</p> <p>      }</p> <p>    }</p> <p>    catch (IOException ex) {</p> <p>      ex.printStackTrace();</p> <p>    }</p> <p>    catch (JDOMException ex) {</p> <p>      ex.printStackTrace();</p> <p>    }</p> <p>  }</p> <p>(3)DOM的document和JDOM的Document之间的相互{换用方法,单!</p> <p>DOMBuilder builder = new DOMBuilder();</p> <p>org.jdom.Document jdomDocument = builder.build(domDocument);</p> <p>DOMOutputter converter = new DOMOutputter();// work with the JDOM document…</p> <p>org.w3c.dom.Document domDocument = converter.output(jdomDocument);</p> <p>// work with the DOM document…</p> <p>2.XML文档输出</p> <p>XMLOutPutterc:</p> <p>JDOM的输出非常灵z?支持很多Uio格式以及风格的输?/p> <p>Document doc = new Document(...);</p> <p>XMLOutputter outp = new XMLOutputter();</p> <p>outp.output(doc, fileOutputStream); // Raw output</p> <p>outp.setTextTrim(true); // Compressed output</p> <p>outp.output(doc, socket.getOutputStream());</p> <p>outp.setIndent(" ");// Pretty output</p> <p>outp.setNewlines(true);</p> <p>outp.output(doc, System.out);</p> <p>详细请参阅最新的JDOM API手册</p> <p>3.Element c:</p> <p>(1)览Element?/p> <p>Element root = doc.getRootElement();//获得根元素element</p> <p>List allChildren = root.getChildren();// 获得所有子元素的一个list</p> <p>List namedChildren = root.getChildren("name");// 获得指定名称子元素的list</p> <p>Element child = root.getChild("name");//获得指定名称的第一个子元素</p> <p>JDOMl了我们很多很灵zȝ使用Ҏ(gu)来管理子元素Q这里的List是java.util.ListQ?/p> <p>List allChildren = root.getChildren();</p> <p>allChildren.remove(3); // 删除W四个子元素</p> <p>allChildren.removeAll(root.getChildren("jack"));// 删除?#8220;jack”的子元素</p> <p>root.removeChildren("jack"); // 便捷写法</p> <p>allChildren.add(new Element("jane"));// 加入</p> <p>root.addContent(new Element("jane")); // 便捷写法</p> <p>allChildren.add(0, new Element("first"));</p> <p>(2)UdElements:</p> <p>在JDOM里很?/p> <p>Element movable = new Element("movable");</p> <p>parent1.addContent(movable); // place</p> <p>parent1.removeContent(movable); // remove</p> <p>parent2.addContent(movable); // add</p> <p>在Dom?/p> <p>Element movable = doc1.createElement("movable");</p> <p>parent1.appendChild(movable); // place</p> <p>parent1.removeChild(movable); // remove</p> <p>parent2.appendChild(movable); // 出错!</p> <p>补充Q纠错?/p> <p>JDOM的Element构造函敎ͼ以及它的其他函数Q会查element是否合法?/p> <p>而它的add/removeҎ(gu)会检查树l构Q检查内容如下:</p> <p>1.在Q何树中是否有回环节点</p> <p>2.是否只有一个根节点</p> <p>3.是否有一致的命名I间QNamespacesQ?</p> <p>(3)Element的text内容d</p> <p><description></p> <p>A cool demo</p> <p></description></p> <p>// The text is directly available</p> <p>// Returns "\n A cool demo\n"</p> <p>String desc = element.getText();</p> <p>// There's a convenient shortcut</p> <p>// Returns "A cool demo"</p> <p>String desc = element.getTextTrim();</p> <p>(4)Elment内容修改</p> <p>element.setText("A new description");</p> <p>3.可正解释特D字W?/p> <p>element.setText("<xml> content");</p> <p>4.CDATA的数据写入、读?/p> <p>element.addContent(new CDATA("<xml> content"));</p> <p>String noDifference = element.getText();</p> <p>混合内容</p> <p>element可能包含很多U内容,比如?/p> <p><table></p> <p><!-- Some comment --></p> <p>Some text</p> <p><tr>Some child element</tr></p> <p></table></p> <p>取table的子元素tr</p> <p>String text = table.getTextTrim();</p> <p>Element tr = table.getChild("tr");</p> <p>也可使用另外一个比较简单的Ҏ(gu)</p> <p>List mixedCo = table.getContent();</p> <p>Iterator itr = mixedCo.iterator();</p> <p>while (itr.hasNext()) {</p> <p>Object o = i.next();</p> <p>if (o instanceof Comment) {...}</p> <p>// q里可以写成Comment, Element, Text, CDATA,ProcessingInstruction, 或者是EntityRef的类?/p> <p>}</p> <p>// 现在U除Comment,注意q里游标应ؓ1。这是由于回车键也被解析成Textcȝ~故,所以Comment应??/p> <p>mixedCo.remove(1); </p> <p>4.Attributec?/p> <p><table width="100%" border="0"> </table></p> <p>String width = table.getAttributeValue("width");//获得attribute</p> <p>int border = table.getAttribute("width").getIntValue();</p> <p>table.setAttribute("vspace", "0");//讄a(chn)ttribute</p> <p>table.removeAttribute("vspace");// 删除一个或全部attribute</p> <p>table.getAttributes().clear(); </p> <p>5.处理指o(Processing Instructions)操作</p> <p>一个Pls的例?/p> <p><?br?></p> <p><?cocoon-process type="xslt"?></p> <p>          |        |</p> <p>          |        |</p> <p>        目标     数据</p> <p>处理目标名称(Target)</p> <p>String target = pi.getTarget();</p> <p>获得所有数据(dataQ,在目标(targetQ以后的所有数据都会被q回?/p> <p>String data = pi.getData();</p> <p>String type = pi.getValue("type");获得指定属性的数据</p> <p>List ls = pi.getNames();获得所有属性的名称</p> <p>6.命名I间操作</p> <p><xhtml:html </p> <p> xmlns:xhtml="http://www.w3.org/1999/xhtml"></p> <p><xhtml:title>Home Page</xhtml:title></p> <p></xhtml:html></p> <p>Namespace xhtml = Namespace.getNamespace("xhtml", "http://www.w3.org/1999/xhtml");</p> <p>List kids = html.getChildren("title", xhtml);</p> <p>Element kid = html.getChild("title", xhtml);</p> <p>kid.addContent(new Element("table", xhtml));</p> <p>7.XSLT格式转换</p> <p>使用以下函数可对XSLT转换</p> <p>最后如果你需要用w3c的Document则需要{换一下?/p> <p>public static Document transform(String stylesheetQDocument in)</p> <p>                                        throws JDOMException {</p> <p>     try {</p> <p>       Transformer transformer = TransformerFactory.newInstance()</p> <p>                             .newTransformer(new StreamSource(stylesheet));</p> <p>       JDOMResult out = new JDOMResult();</p> <p>       transformer.transform(new JDOMSource(in), out);</p> <p>       return out.getDeocument();</p> <p>     }</p> <p>     catch (TransformerException e) {</p> <p>       throw new JDOMException("XSLT Trandformation failed", e);</p> <p>     }</p> <p>   }</p> <p>五、用?</p> <p>1、生成xml文档Q?/p> <p> </p> <p> </p> <p>public class WriteXML{</p> <p>    public void BuildXML() throws Exception {</p> <p>        Element root,student,number,name,age;         </p> <p>        root = new Element("student-info"); //生成根元素:student-info</p> <p>        student = new Element("student"); //生成元素Qstudent(number,name,age)                             </p> <p>        number = new Element("number");</p> <p>        name = new Element("name");</p> <p>        age = new Element("age");</p> <p>        Document doc = new Document(root); //根元素植入文档doc?/p> <p>        number.setText("001");</p> <p>        name.setText("lnman");</p> <p>        age.setText("24");</p> <p>        student.addContent(number);</p> <p>        student.addContent(name);</p> <p>        student.addContent(age);</p> <p>        root.addContent(student);</p> <p>        Format format = Format.getCompactFormat();</p> <p>        format.setEncoding("gb2312"); //讄xml文g的字Wؓgb2312</p> <p>        format.setIndent("    "); //讄xml文g的羃qؓ4个空?/p> <p>        XMLOutputter XMLOut = new XMLOutputter(format);//元素后换行一层元素羃四格 </p> <p>        XMLOut.output(doc, new FileOutputStream("studentinfo.xml"));  </p> <p>}</p> <p>    public static void main(String[] args) throws Exception {</p> <p>        WriteXML w = new WriteXML();</p> <p>        System.out.println("Now we build an XML document .....");</p> <p>        w.BuildXML();</p> <p>        System.out.println("finished!");</p> <p>}</p> <p>}</p> <p>生成的xml文档为:</p> <p><?xml version="1.0" encoding="gb2312"?></p> <p><student-info></p> <p>    <student></p> <p>        <number>001</number></p> <p>        <name>lnman</name></p> <p>        <age>24</age></p> <p>    </student></p> <p></student-info></p> <p> </p> <p> </p> <p>创徏XML文档2Q?/p> <p> public class CreateXML {</p> <p>  public void Create() {</p> <p>   try {</p> <p>    Document doc = new Document();   </p> <p>    ProcessingInstruction pi=new ProcessingInstruction("xml-stylesheet","type="text/xsl" href="test.xsl"");</p> <p>    doc.addContent(pi);    </p> <p>    Namespace ns = Namespace.getNamespace("http://www.bromon.org" );</p> <p>    Namespace ns2 = Namespace.getNamespace("other", "http://www.w3c.org" );</p> <p>    Element root = new Element("根元?, ns);</p> <p>    root.addNamespaceDeclaration(ns2);</p> <p>    doc.setRootElement(root);</p> <p>    Element el1 = new Element("元素一");</p> <p>    el1.setAttribute("属?, "属性一");    </p> <p>    Text text1=new Text("元素?);</p> <p>             Element em = new Element("元素?).addContent("W二个元?);</p> <p>    el1.addContent(text1);</p> <p>             el1.addContent(em);             </p> <p>             Element el2 = new Element("元素?).addContent("W三个元?);</p> <p>             root.addContent(el1);</p> <p>             root.addContent(el2);             </p> <p>             //~进四个I格,自动换行,gb2312~码</p> <p>             XMLOutputter outputter = new XMLOutputter("  ", true,"GB2312");</p> <p>             outputter.output(doc, new FileWriter("test.xml"));</p> <p>         }catch(Exception e)  {</p> <p>          System.out.println(e);</p> <p>         }</p> <p>     }     </p> <p>     public static void main(String args[]) {</p> <p>      new CreateXML().Create();</p> <p>     }     </p> <p> }</p> <p>2、读取xml文档的例子:</p> <p>import org.jdom.output.*;</p> <p>import org.jdom.input.*;</p> <p>import org.jdom.*;</p> <p>import java.io.*;</p> <p>import java.util.*;</p> <p>public class ReadXML{</p> <p>    public static void main(String[] args) throws Exception {</p> <p>        SAXBuilder builder = new SAXBuilder();</p> <p>        Document read_doc = builder.build("studentinfo.xml");</p> <p>        Element stu = read_doc.getRootElement();</p> <p>        List list = stu.getChildren("student");</p> <p>        for(int i = 0;i < list.size();i++) {</p> <p>            Element e = (Element)list.get(i);</p> <p>            String str_number = e.getChildText("number");</p> <p>            String str_name = e.getChildText("name");</p> <p>            String str_age = e.getChildText("age");</p> <p>            System.out.println("---------STUDENT--------------");</p> <p>            System.out.println("NUMBER:" + str_number);</p> <p>            System.out.println("NAME:" + str_name);</p> <p>            System.out.println("AGE:" + str_age);</p> <p>            System.out.println("------------------------------");</p> <p>            System.out.println();</p> <p>        }  </p> <p>       }</p> <p>}</p> <p>3、DTD验证的:</p> <p> public class XMLWithDTD {</p> <p>  public void validate()  {</p> <p>   try {</p> <p>    SAXBuilder builder = new SAXBuilder(true);</p> <p>    builder.setFeature("http://xml.org/sax/features/validation";,true); </p> <p>    Document doc = builder.build(new FileReader("author.xml"));    </p> <p>    System.out.println("搞掂");</p> <p>    XMLOutputter outputter = new XMLOutputter();</p> <p>    outputter.output(doc, System.out);</p> <p>   }catch(Exception e) {</p> <p>    System.out.println(e);</p> <p>   }   </p> <p>  }</p> <p>  public static void main(String args[]) {</p> <p>   new XMLWithDTD().validate();</p> <p>  }  </p> <p> }</p> <p>   需要说明的是,q个E序没有指明使用哪个DTD文g。DTD文g的位|是在XML中指定的Q? 且DTD不支持命名空_一个XML只能引用一个DTDQ所以程序直接读取XML中指定的DTDQ程序本w不用指定。不q这样一来,好象只能用外部式 的DTD引用方式了?高h指点?/p> <p> </p> <p> </p> <p>4、XML Schema验证的:</p> <p> public class XMLWithSchema {</p> <p>  String xml="test.xml";</p> <p>  String schema="test-schema.xml";</p> <p>  public void validate() {</p> <p>   try {</p> <p>    SAXBuilder builder = new SAXBuilder(true);</p> <p>    //指定U束方式为XML schema</p> <p>    builder.setFeature("http://apache.org/xml/features/validation/schema";,  true);</p> <p>    //导入schema文g</p> <p>builder.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation";,schema); </p> <p>    Document doc = builder.build(new FileReader(xml));    </p> <p>    System.out.println("搞掂");</p> <p>    XMLOutputter outputter = new XMLOutputter();</p> <p>    outputter.output(doc, System.out);</p> <p>   }catch(Exception e) {</p> <p>    System.out.println("验证p|:"+e);</p> <p>   }  </p> <p>  } </p> <p> }</p> <p> 上面的程序就指出了要引入的XML Schema文g的位|?/p> <p> </p> <p> </p> <p> pȝ默认输出是UTF-8Q这有可能导致出Cؕ码?/p> <p>5、Xpath例子Q?/p> <p>JDOM的关于XPATH的api在org.jdom.xpathq个包里。这个包下,有一个抽象类 XPath.java和实现类JaxenXPath.javaQ?使用时先用XPathcȝ静态方法newInstance(String xpath)得到XPath对象Q然后调用它的selectNodes(Object context)Ҏ(gu)或selectSingleNode(Object context)Ҏ(gu)Q前者根据xpath语句q回一l节?List对象)Q后者根据一个xpath语句q回W合条g的第一个节?Objectc? ?。请看jdom-1.0自带的范例程序: </p> <p>     它分析在web.xml文g中的注册的servlet的个数及参数个数Qƈ输出角色名?</p> <p>web.xml文gQ?</p> <p><?xml version="1.0" encoding="ISO-8859-1"?> </p> <p><!-- </p> <p><!DOCTYPE web-app </p> <p>    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" </p> <p>    "http://java.sun.com/j2ee/dtds/web-app_2.2.dtd"> </p> <p>--> </p> <p><web-app> </p> <p>    <servlet> </p> <p>        <servlet-name>snoop</servlet-name> </p> <p>        <servlet-class>SnoopServlet</servlet-class> </p> <p>    </servlet> </p> <p>    <servlet> </p> <p>        <servlet-name>file </servlet-name> </p> <p>        <servlet-class>ViewFile</servlet-class> </p> <p>        <init-param> </p> <p>            <param-name>initial</param-name> </p> <p>            <param-value>1000</param-value> </p> <p>            <description>The initial value for the counter  <!-- optional --></description> </p> <p>        </init-param> </p> <p>    </servlet> </p> <p>    <servlet-mapping> </p> <p>        <servlet-name>mv</servlet-name> </p> <p>        <url-pattern>*.wm</url-pattern> </p> <p>    </servlet-mapping> </p> <p>    <distributed/> </p> <p>    <security-role> </p> <p>      <role-name>manager</role-name> </p> <p>      <role-name>director</role-name> </p> <p>      <role-name>president</role-name> </p> <p>    </security-role> </p> <p></web-app> </p> <p>处理E序Q?</p> <p>import java.io.*; </p> <p>import java.util.*;  </p> <p>public class XPathReader {      </p> <p>    public static void main(String[] args) throws IOException, JDOMException { </p> <p>        if (args.length != 1) { </p> <p>            System.err.println("Usage: java XPathReader web.xml"); </p> <p>            return; </p> <p>        } </p> <p>        String filename = args[0];//从命令行输入web.xml </p> <p>        PrintStream out = System.out; </p> <p>        SAXBuilder builder = new SAXBuilder(); </p> <p>        Document doc = builder.build(new File(filename));//得到Document对象 </p> <p> </p> <p> </p> <p>        // Print servlet information </p> <p>        XPath servletPath = XPath.newInstance("http://servlet");//,选择L路径下servlet元素 </p> <p>        List servlets = servletPath.selectNodes(doc);//q回所有的servlet元素?/p> <p>        out.println("This WAR has "+ servlets.size() +" registered servlets:"); </p> <p>        Iterator i = servlets.iterator(); </p> <p>        while (i.hasNext()) {//输出servlet信息 </p> <p>            Element servlet = (Element) i.next(); </p> <p>            out.print("\t" + servlet.getChild("servlet-name") </p> <p>                                    .getTextTrim() + </p> <p>                      " for " + servlet.getChild("servlet-class") </p> <p>                                       .getTextTrim()); </p> <p>            List initParams = servlet.getChildren("init-param"); </p> <p>            out.println(" (it has " + initParams.size() + " init params)");  </p> <p>        }              </p> <p>        // Print security role information </p> <p>        XPath rolePath = XPath.newInstance("http://security-role/role-name/text()"); </p> <p>        List roleNames = rolePath.selectNodes(doc);//得到所有的角色?</p> <p>        if (roleNames.size() == 0) { </p> <p>            out.println("This WAR contains no roles"); </p> <p>        } else { </p> <p>            out.println("This WAR contains " + roleNames.size() + " roles:"); </p> <p>            i = roleNames.iterator(); </p> <p>            while (i.hasNext()) {//输出角色?</p> <p>                out.println("\t" + ((Text)i.next()).getTextTrim()); </p> <p>            } </p> <p>        } </p> <p>    }     </p> <p>} </p> <p> </p> <p> </p> <p>输出l果: </p> <p>C:\java>java   XPathReader web.xml </p> <p>This WAR has 2 registered servlets: </p> <p>        snoop for SnoopServlet (it has 0 init params) </p> <p>        file for ViewFile (it has 1 init params) </p> <p>This WAR contains 3 roles: </p> <p>        manager </p> <p>        director </p> <p>        president</p> <p> </p> <p> </p> <p>6、数据输入要用到XML文档要通过org.jdom.input包,反过来需要org.jdom.output。如前面所_x看API文档p够用?</p> <p>我们的例子读入XML文gexampleA.xmlQ加入一条处理指令,修改W一本书的h(hun)格和作者,q添加一条属性,然后写入文gexampleB.xmlQ?</p> <p>//exampleA.xml </p> <p><?xml version="1.0" encoding="GBK"?> </p> <p><bookList> </p> <p><book> </p> <p><name>Java~程入门</name> </p> <p><author>张三</author> </p> <p><publishDate>2002-6-6</publishDate> </p> <p><price>35.0</price> </p> <p></book> </p> <p><book> </p> <p><name>XML在Java中的应用</name> </p> <p><author>李四</author> </p> <p><publishDate>2002-9-16</publishDate> </p> <p><price>92.0</price> </p> <p></book> </p> <p></bookList> </p> <p>//testJDOM.java </p> <p>import org.jdom.*; </p> <p>import org.jdom.output.*; </p> <p>import org.jdom.input.*; </p> <p>import java.io.*; </p> <p>public class TestJDOM{ </p> <p>public static void main(String args[])throws Exception{ </p> <p>SAXBuilder sb = new SAXBuilder(); </p> <p>//从文件构造一个DocumentQ因为XML文g中已l指定了~码Q所以这里不必了 </p> <p>Document doc = sb.build(new FileInputStream("exampleA.xml")); </p> <p>ProcessingInstruction pi = new ProcessingInstruction//加入一条处理指?</p> <p>("xml-stylesheet","href=\"bookList.html.xsl\" type=\"text/xsl\""); </p> <p>doc.addContent(pi); </p> <p>Element root = doc.getRootElement(); //得到根元?</p> <p>java.util.List books = root.getChildren(); //得到根元素所有子元素的集?</p> <p>Element book = (Element)books.get(0); //得到W一个book元素 </p> <p>//为第一本书d一条属?</p> <p>Attribute a = new Attribute("hot","true"); </p> <p>book.setAttribute(a); </p> <p>Element author = book.getChild("author"); //得到指定的字元素 </p> <p>author.setText("王五"); //作者改为王?</p> <p>//?Text t = new Text("王五");book.addContent(t); </p> <p>Element price = book.getChild("price"); //得到指定的字元素 </p> <p>//修改hQ比较郁L(fng)是我们必自p{换数据类型,而这正是JAXB的优?</p> <p>author.setText(Float.toString(50.0f)); </p> <p>String indent = " "; </p> <p>boolean newLines = true; </p> <p>XMLOutputter outp = new XMLOutputter(indent,newLines,"GBK"); </p> <p>outp.output(doc, new FileOutputStream("exampleB.xml")); </p> <p>} </p> <p>}; </p> <p>执行l果exampleB.xmlQ?</p> <p><?xml version="1.0" encoding="GBK"?> </p> <p><bookList> </p> <p><book hot=”true”> </p> <p><name>Java~程入门</name> </p> <p><author>50.0</author> </p> <p><publishDate>2002-6-6</publishDate> </p> <p><price>35.0</price> </p> <p></book> </p> <p><book> </p> <p><name>XML在Java中的应用</name> </p> <p><author>李四</author> </p> <p><publishDate>2002-9-16</publishDate> </p> <p><price>92.0</price> </p> <p></book> </p> <p></bookList> </p> <p><?xml-stylesheet href="bookList.html.xsl" type="text/xsl"?> </p> <p>在默认情况下QJDOM的ElementcȝgetText()q类的方法不会过滤空白字W,如果你需要过滤,用setTextTrim() ?/p> </div><img src ="http://www.aygfsteel.com/flustar/aggbug/114561.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.aygfsteel.com/flustar/" target="_blank">flustar</a> 2007-04-29 14:08 <a href="http://www.aygfsteel.com/flustar/archive/2007/04/29/114561.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item></channel></rss> <footer> <div class="friendship-link"> <a href="http://www.aygfsteel.com/" title="狠狠久久亚洲欧美专区_中文字幕亚洲综合久久202_国产精品亚洲第五区在线_日本免费网站视频">狠狠久久亚洲欧美专区_中文字幕亚洲综合久久202_国产精品亚洲第五区在线_日本免费网站视频</a> </div> </footer> վ֩ģ壺 <a href="http://" target="_blank">Ĵʡ</a>| <a href="http://" target="_blank"></a>| <a href="http://" target="_blank">ɳ</a>| <a href="http://" target="_blank">ɯ</a>| <a href="http://" target="_blank">Ԫ</a>| <a href="http://" target="_blank"></a>| <a href="http://" target="_blank">¤</a>| <a href="http://" target="_blank"></a>| <a href="http://" target="_blank">ڶ</a>| <a href="http://" target="_blank"></a>| <a href="http://" target="_blank">̩</a>| <a href="http://" target="_blank">ƽ</a>| <a href="http://" target="_blank"></a>| <a href="http://" target="_blank"></a>| <a href="http://" target="_blank"></a>| <a href="http://" target="_blank">ϲ</a>| <a href="http://" target="_blank"></a>| <a href="http://" target="_blank"></a>| <a href="http://" target="_blank"></a>| <a href="http://" target="_blank">ƽԶ</a>| <a href="http://" target="_blank">ƽ</a>| <a href="http://" target="_blank">Ȫ</a>| <a href="http://" target="_blank"></a>| <a href="http://" target="_blank"></a>| <a href="http://" target="_blank">̨</a>| <a href="http://" target="_blank"></a>| <a href="http://" target="_blank">ʵ</a>| <a href="http://" target="_blank"></a>| <a href="http://" target="_blank">ؼ</a>| <a href="http://" target="_blank"></a>| <a href="http://" target="_blank"></a>| <a href="http://" target="_blank"></a>| <a href="http://" target="_blank">ƺ</a>| <a href="http://" target="_blank">ݸ</a>| <a href="http://" target="_blank">̴</a>| <a href="http://" target="_blank">¤</a>| <a href="http://" target="_blank">̨ʡ</a>| <a href="http://" target="_blank">ͷ</a>| <a href="http://" target="_blank">˰</a>| <a href="http://" target="_blank">̨</a>| <a href="http://" target="_blank"></a>| <script> (function(){ var bp = document.createElement('script'); var curProtocol = window.location.protocol.split(':')[0]; if (curProtocol === 'https') { bp.src = 'https://zz.bdstatic.com/linksubmit/push.js'; } else { bp.src = 'http://push.zhanzhang.baidu.com/push.js'; } var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(bp, s); })(); </script> </body>