??xml version="1.0" encoding="utf-8" standalone="yes"?>91精品啪在线观看国产18,久久亚洲风情,女同一区二区三区http://www.aygfsteel.com/huhu/category/1842.htmlHuhu'Blogzh-cnThu, 01 Mar 2007 21:10:18 GMTThu, 01 Mar 2007 21:10:18 GMT60JDOM使用详解及实?/title><link>http://www.aygfsteel.com/huhu/articles/11866.html</link><dc:creator>似水年</dc:creator><author>似水年</author><pubDate>Sat, 03 Sep 2005 02:26:00 GMT</pubDate><guid>http://www.aygfsteel.com/huhu/articles/11866.html</guid><wfw:comment>http://www.aygfsteel.com/huhu/comments/11866.html</wfw:comment><comments>http://www.aygfsteel.com/huhu/articles/11866.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.aygfsteel.com/huhu/comments/commentRss/11866.html</wfw:commentRss><trackback:ping>http://www.aygfsteel.com/huhu/services/trackbacks/11866.html</trackback:ping><description><![CDATA[<P>一、JDOM ?/P> <P>JDOM是一个开源项目,它基于树型结构,利用UJAVA的技术对XML文实现解析、生成、序列化以及多种操作?/P> <P>JDOM 直接为JAVA~程服务。它利用更ؓ强有力的JAVA语言的诸多特性(Ҏ重蝲、集合概念以及映)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?BR><BR>org.jdom.adapters         包含了与dom适配的javac?/P> <P>org.jdom.filter            包含了xml文的过滤器c?/P> <P>org.jdom.input            包含了读取xml文的类</P> <P>org.jdom.output           包含了写入xml文的类</P> <P>org.jdom.transform        包含了将jdom xml文接口转换为其他xml文接口</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("<A );</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>以下如无Ҏ均指JDOM里的Document?/P> <P>四、JDOM主要使用Ҏ</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ȝ使用Ҏ来管理子元素Q这里的List是java.util.ListQ?/P> <P>List allChildren = root.getChildren();</P> <P>allChildren.remove(3); // 删除W四个子元素</P> <P>allChildren.removeAll(root.getChildren("jack"));// 删除叫“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Ҏ会检查树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>也可使用另外一个比较简单的Ҏ</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");//讄attribute</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="<A ></P> <P><xhtml:title>Home Page</xhtml:title></P> <P></xhtml:html></P> <P>Namespace xhtml = Namespace.getNamespace("xhtml", "<A );</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("<A );</P> <P>    Namespace ns2 = Namespace.getNamespace("other", "<A );</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("<A ;,true</A>); </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("<A ;,  true);</P> <P>    //导入schema文g</P> <P>builder.setProperty("<A ;,schema</A>); </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)Ҏ或selectSingleNode(Object context)ҎQ前者根据xpath语句q回一l节?List对象)Q后者根据一个xpath语句q回W合条g的第一个节?Objectcd)。请看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>    "<A > </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格和作者,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是我们必自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?gt; </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><img src ="http://www.aygfsteel.com/huhu/aggbug/11866.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.aygfsteel.com/huhu/" target="_blank">似水年</a> 2005-09-03 10:26 <a href="http://www.aygfsteel.com/huhu/articles/11866.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>JDom使用详解 http://www.aygfsteel.com/huhu/articles/6679.html似水年似水年Fri, 24 Jun 2005 07:26:00 GMThttp://www.aygfsteel.com/huhu/articles/6679.htmlhttp://www.aygfsteel.com/huhu/comments/6679.htmlhttp://www.aygfsteel.com/huhu/articles/6679.html#Feedback0http://www.aygfsteel.com/huhu/comments/commentRss/6679.htmlhttp://www.aygfsteel.com/huhu/services/trackbacks/6679.html 1、创建XML文Q?BR> 

import java.io.*;
 import org.jdom.
*;
 import org.jdom.input.
*;
 import org.jdom.output.
*;

 
public class CreateXML
 
{
  
public void Create()
  
{
   
try
   
{
    Document doc 
= new Document();   
    ProcessingInstruction pi
=new ProcessingInstruction("xml-stylesheet","type="text/xsl" href="test.xsl"");
    doc.addContent(pi);
    
    Namespace ns 
= Namespace.getNamespace("http://www.bromon.org" );
    Namespace ns2 
= Namespace.getNamespace("other""http://www.w3c.org" );

    Element root 
= new Element("根元?/SPAN>", ns);
    root.addNamespaceDeclaration(ns2);
    doc.setRootElement(root);
    Element el1 
= new Element("元素一");
    el1.setAttribute(
"属?/SPAN>""属性一");
    
    Text text1
=new Text("元素?/SPAN>");
             Element em 
= new Element("元素?/SPAN>").addContent("W二个元?/SPAN>");

    el1.addContent(text1);
             el1.addContent(em);
             
             Element el2 
= new Element("元素?/SPAN>").addContent("W三个元?/SPAN>");

             root.addContent(el1);
             root.addContent(el2);
             
             
//~进四个I格,自动换行,gb2312~码
             XMLOutputter outputter = new XMLOutputter("  "true,"GB2312");
             outputter.output(doc, 
new FileWriter("test.xml"));
         }
catch(Exception e)
         
{
          System.
out.println(e);
         }

     }

     
     
public static void main(String args[])
     
{
      
new CreateXML().Create();
     }

     
 }


 2、DTD验证的:
 

import java.io.*;
 import org.jdom.
*;
 import org.jdom.input.
*;
 import org.jdom.output.
*;

 
public class XMLWithDTD
 
{
  
public void validate()
  
{
   
try
   
{
    SAXBuilder builder 
= new SAXBuilder(true);
    builder.setFeature(
"http://xml.org/sax/features/validation";,true); 
    Document doc 
= builder.build(new FileReader("author.xml"));
    
    System.
out.println("搞掂");
    XMLOutputter outputter 
= new XMLOutputter();
    outputter.output(doc, System.
out);
   }
catch(Exception e)
   
{
    System.
out.println(e);
   }

   
  }

  
public static void main(String args[])
  
{
   
new XMLWithDTD().validate();
  }

  
 }


 需要说明的是,q个E序没有指明使用哪个DTD文g。DTD文g的位|是在XML中指定的Q而且DTD不支持命名空_一个XML只能引用一个DTDQ所以程序直接读取XML中指定的DTDQ程序本w不用指定。不q这样一来,好象只能用外部式的DTD引用方式了?高h指点?/P>

 3、XML Schema验证的:

 import java.io.*;
 import org.jdom.
*;
 import org.jdom.input.
*;
 import org.jdom.output.
*;

 
public class XMLWithSchema
 
{
  String xml
="test.xml";
  String schema
="test-schema.xml";
  
public void validate()
  
{
   
try
   
{
    SAXBuilder builder 
= new SAXBuilder(true);
    
//指定U束方式为XML schema
    builder.setFeature("http://apache.org/xml/features/validation/schema";,  true);
    
//导入schema文g
    builder.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation";,schema); 
    Document doc 
= builder.build(new FileReader(xml));
    
    System.
out.println("搞掂");
    XMLOutputter outputter 
= new XMLOutputter();
    outputter.output(doc, System.
out);
   }
catch(Exception e)
   
{
    System.
out.println("验证p|:"+e);
   }

   
  }

  
 }


 上面的程序就指出了要引入的XML Schema文g的位|?/P>

 pȝ默认输出是UTF-8Q这有可能导致出Cؕ码?/P>

 读XML文的技巧在|上已经泛滥Q这里就没有再列出来?/P>

似水年 2005-06-24 15:26 发表评论
]]>
վ֩ģ壺 ̫| ƽ| | | | | | ղ| | | | ̨| | Ĭ| | | | ֦| | µ| | | | ˮ| | | Ͻ| ƽ| ˮ| | | н| | | º| ʤ| | ֳ| | | ϻ|