CSDN首页 空间 新闻 论坛 Blog 下载 读书 网摘 搜索 .NET Java 视频 接项目 求职 在线学习 买书 程序员 通知
山寨机中的战斗机! 程序优化工程师到底对IT界有没有贡献
CSDN社区
搜索 收藏 打印 关闭
CSDN社区 >  Java >  Web Services / XML

求例子,用JDOM处理XML文档

楼主fengyuxi(koala)2002-08-13 11:30:25 在 Java / Web Services / XML 提问

有一些方法,  
  比如给参数:elemnetname,attributename  
  返回:attributevlaue  
   
  再比如  
  给参数:elementname,attributename,attributevalue  
  处理结果:在elementname中加入属性:attributename="attributevalue"  
   
  请大虾给几个例子,谢谢! 问题点数:100、回复次数:7Top

1 楼binriyue(无)回复于 2002-08-13 11:34:23 得分 20

http://safari.informit.com/main.asp?bookname=javaxml2&cnode=1的有一本java   and   xml的书,其中第七、八章就是专门讲解jdom的。  
  http://www.cafeconleche.org/books/xmljava/这里也有讲JDOM的。Top

2 楼soldier1002(古代士兵)回复于 2002-08-13 11:55:00 得分 30

//use   jdom   for   xml   parsing  
  /*  
  import   javax.xml.parsers.*;  
   
  import   org.w3c.dom.*;  
  import   org.xml.sax.*;  
   
  import   org.jdom.Attribute;  
  import   org.jdom.Comment;  
  import   org.jdom.Document;  
  import   org.jdom.Element;  
  import   org.jdom.JDOMException;  
  import   org.jdom.input.DOMBuilder;  
  import   org.jdom.output.XMLOutputter;  
   
  public   class   ConfigParser   {  
        org.jdom.Document   document;  
        org.jdom.Element   rootElement;  
        static   String   configFile=   "Ico-opData/ico-opCRMconfig.xml";  
   
        public   ConfigParser(){  
              try{  
                      DOMBuilder   builder   =   new   DOMBuilder();  
                      document   =   builder.build(getW3CDocument());  
                      rootElement   =   document.getRootElement();  
                  //}catch(JDOMException   e)   {  
                        //   e.printStackTrace();  
                  }catch(NullPointerException   e)   {  
                          e.printStackTrace();  
                  }catch(Exception   e){  
                  }  
        }  
   
      public   org.w3c.dom.Document     getW3CDocument(){  
                  org.w3c.dom.Document   myDoc;  
                  File   inputfile   =   new   File(configFile);  
                      try{  
                          DocumentBuilderFactory   dbf   =   DocumentBuilderFactory.newInstance();  
                          DocumentBuilder   db   =   dbf.newDocumentBuilder();  
                          myDoc   =   db.parse(inputfile);  
                          return   myDoc;  
                      }catch(FileNotFoundException   fe){  
                              System.out.println("File   no   found:   "   +   fe.getMessage());  
                      }catch(IOException   ioe){  
                              System.err.println(ioe.getMessage());  
                      }catch(ParserConfigurationException   pe){  
                              System.err.println(pe.getMessage());  
                      }catch(SAXException   se){  
                              System.err.println(se.getMessage());  
                      }catch(Exception   e){  
                      }  
                      return   null;  
      }  
   
   
      public   Object[][]   getAllSystemConfiguration(){  
          List   childList   =   rootElement.getChildren();  
          Object[][]   configData   =   new   Object[childList.size()][4];  
   
          Iterator   it   =   childList.iterator();  
          int   i   =   0;  
          while(it.hasNext()){  
              Element   currentElement   =   (Element)it.next();  
              List     parameterChildList   =   currentElement.getChildren();  
              Iterator   pit   =   parameterChildList.iterator();  
              String   parameterName   =   currentElement.getChild("ParameterName").getText().trim();  
              String   parameterValue   =   currentElement.getChild("ParameterValue").getText().trim();  
              String   parameterDes   =   currentElement.getChild("Description").getText().trim();  
              Boolean   passwordDisplay   =   new   Boolean(currentElement.getChild("PasswordDisplay").getText().trim());  
              configData[i][0]   =   parameterName;  
              configData[i][1]   =   parameterValue;  
              configData[i][2]   =   parameterDes;  
              configData[i][3]   =   passwordDisplay;  
              i   =   i   +1;  
          }  
          return   configData;  
          }  
   
      public   String   getParameterValue(String   queryParameterName){  
          List   childList   =   rootElement.getChildren();  
          Iterator   it   =   childList.iterator();  
          while(it.hasNext()){  
              Element   currentElement   =   (Element)it.next();  
              List     parameterChildList   =   currentElement.getChildren();  
              Iterator   pit   =   parameterChildList.iterator();  
              String   parameterName   =   currentElement.getChild("ParameterName").getText().trim();  
              if(parameterName.equals(queryParameterName)){  
                  return   currentElement.getChild("ParameterValue").getText().trim();  
              }  
          }  
          return   null;  
        }  
   
      public   String   getParameterDescription(String   queryParameterName){  
          List   childList   =   rootElement.getChildren();  
          Iterator   it   =   childList.iterator();  
          while(it.hasNext()){  
              Element   currentElement   =   (Element)it.next();  
              List     parameterChildList   =   currentElement.getChildren();  
              Iterator   pit   =   parameterChildList.iterator();  
              String   parameterName   =   currentElement.getChild("ParameterName").getText().trim();  
              if(parameterName.equals(queryParameterName)){  
                  return   currentElement.getChild("Description").getText().trim();  
              }  
          }  
          return   null;  
      }  
   
      public   boolean   setParameterDescription(String   queryParameterName,  
          String   parameterValue){return   true;}  
   
      public   boolean   setAllParameters(String[][]   parameters)   throws   IOException{  
              List   childList   =   rootElement.getChildren();  
   
              for(int   i   =0;   i<parameters.length   ;   i++){  
                  Iterator   it   =   childList.iterator();  
                  while(it.hasNext()){  
                          Element   currentElement   =   (Element)it.next();  
                          List     parameterChildList   =   currentElement.getChildren();  
                          Iterator   pit   =   parameterChildList.iterator();  
                          String   parameterName   =   currentElement.getChild("ParameterName").getText().trim();  
   
                          if(parameterName.equals(parameters[i][0])){  
                              Element   pValueElement=   currentElement.getChild("ParameterValue");  
                              Element   pDescElement   =   currentElement.getChild("Description");  
                              Element   pPasswordElement   =   currentElement.getChild("PasswordDisplay");  
                              pValueElement.setText(parameters[i][1]);  
                              pDescElement.setText(parameters[i][2]);  
                              pPasswordElement.setText(parameters[i][3]);  
                              break;  
                          }  
                      }//while  
                  }//for  
                  saveXMLFile();  
          return   true;  
      }  
   
        private   void   saveXMLFile(){  
            try{  
                  org.jdom.output.XMLOutputter   xmlOut;  
                  document.setDocType(   null   );   //  
                  xmlOut   =   new   org.jdom.output.XMLOutputter();  
                  xmlOut.setTextNormalize(   true   );  
   
                  FileOutputStream   out   =   new   FileOutputStream(configFile);  
                  xmlOut.output(   document,   out   );  
                  out.close();  
              } catch(Exception   tEx   ){  
                      System.out.println("TransformerException:   "+tEx.getMessage());  
                      tEx.printStackTrace();  
              }  
      }Top

3 楼soldier1002(古代士兵)回复于 2002-08-13 11:55:28 得分 0

<Parameters>  
          <Parameter>  
                  <ParameterName>  
                          DBServer  
                  </ParameterName>  
                  <ParameterValue>  
                          localHost  
                  </ParameterValue>  
                  <Description>  
                          Address   of   database   server  
                  </Description>  
          </Parameter>  
          ......more   parameters   can   be   added   here  
      </Parameters>Top

4 楼fengyuxi(koala)回复于 2002-08-13 12:00:01 得分 0

我试试看!Top

5 楼Dickensi(流星·逐日)(★★★★)回复于 2002-08-13 12:45:51 得分 30

(二)获得并安装JDOM  
  在http://jdom.org可以下载JDOM的最新版本。以JDOM   beta8的2进制版本为例。下载后解压缩,JDOM的jar文件就是build目录下的文件jdom.jar,将之加入类路径。另外JDOM还需要lib目录下那些jar文件如xerces.jar的支持。如果在使用中出现以下错误:  
  java.lang.NoSuchMethodError  
  或    
  java.lang.NoClassDefFoundError:   org/xml/sax/SAXNotRecognizedException  
  你需要保证xerces.jar文件在CLASSPATH中位于其他XML类,如JAXP或Crimson之前,这些类文件,包括以前老版本的xerces,可能不支持SAX2.0或DOM   Level   2。于是导致了上面的错误。  
   
  (三)一个简单的例子  
  JDOM的处理方式有些类似于DOM,但它主要是用SAX实现的,你不必担心处理速度和内存的问题。另外,JDOM中几乎没有接口,的类全部是实实在在的类,没有类工厂类的。其最重要的一个包org.jdom中主要有以下类:  
  ?   Attribute  
  ?   CDATA  
  ?   Comment  
  ?   DocType  
  ?   Document  
  ?   Element  
  ?   EntityRef  
  ?   Namespace  
  ?   ProcessingInstruction  
  ?   Text  
  数据输入要用到XML文档要通过org.jdom.input包,反过来需要org.jdom.output。如前面所说,关是看API文档就能够使用。  
  我们的例子读入XML文件exampleA.xml,加入一条处理指令,修改第一本书的价格和作者,并添加一条属性,然后写入文件exampleB.xml:  
  //exampleA.xml  
  <?xml   version="1.0"   encoding="GBK"?>  
  <bookList>  
          <book>  
                  <name>Java编程入门</name>  
                  <author>张三</author>  
                  <publishDate>2002-6-6</publishDate>  
                  <price>35.0</price>  
          </book>  
          <book>  
                  <name>XML在Java中的应用</name>  
                  <author>李四</author>  
                  <publishDate>2002-9-16</publishDate>  
                  <price>92.0</price>  
          </book>  
  </bookList>  
   
  //testJDOM.java  
  import   org.jdom.*;  
  import   org.jdom.output.*;  
  import   org.jdom.input.*;  
  import   java.io.*;  
  public   class   TestJDOM{  
          public   static   void   main(String   args[])throws   Exception{  
                   
                  SAXBuilder   sb   =   new   SAXBuilder();  
   
                  //从文件构造一个Document,因为XML文件中已经指定了编码,所以这里不必了  
                  Document   doc   =   sb.build(new   FileInputStream("exampleA.xml"));  
                   
                  //加入一条处理指令  
                  ProcessingInstruction   pi   =   new   ProcessingInstruction  
                          ("xml-stylesheet","href=\"bookList.html.xsl\"   type=\"text/xsl\"");  
                  doc.addContent(pi);  
   
   
                  Element   root   =   doc.getRootElement();   //得到根元素  
                  java.util.List   books   =   root.getChildren();   //得到根元素所有子元素的集合  
                  Element   book   =   (Element)books.get(0);   //得到第一个book元素  
                  //为第一本书添加一条属性  
                  Attribute   a   =   new   Attribute("hot","true");      
                  book.setAttribute(a);  
                  Element   author   =   book.getChild("author");   //得到指定的字元素  
                  author.setText("王五");   //将作者改为王五  
                  //或   Text   t   =   new   Text("王五");book.addContent(t);  
                  Element   price   =   book.getChild("price");   //得到指定的字元素  
                  //修改价格,比较郁闷的是我们必须自己转换数据类型,而这正是JAXB的优势  
                  author.setText(Float.toString(50.0f));    
                   
   
   
                  String   indent   =   "         ";  
                  boolean   newLines   =   true;  
                  XMLOutputter   outp   =   new   XMLOutputter(indent,newLines,"GBK");  
                  outp.output(doc,   new   FileOutputStream("exampleB.xml"));  
   
          }  
  };  
   
  执行结果exampleB.xml:  
  <?xml   version="1.0"   encoding="GBK"?>  
  <bookList>  
          <book   hot=”true”>  
                  <name>Java编程入门</name>  
                  <author>50.0</author>  
                  <publishDate>2002-6-6</publishDate>  
                  <price>35.0</price>  
          </book>  
          <book>  
                  <name>XML在Java中的应用</name>  
                  <author>李四</author>  
                  <publishDate>2002-9-16</publishDate>  
                  <price>92.0</price>  
          </book>  
  </bookList>  
  <?xml-stylesheet   href="bookList.html.xsl"   type="text/xsl"?>  
   
  在默认情况下,JDOM的Element类的getText()这类的方法不会过滤空白字符,如果你需要过滤,用setTextTrim()   。  
   
   
  Top

6 楼demonangel(demon)回复于 2002-08-13 13:15:59 得分 20

Jdom   是比较好,可是按你的要求   直接用XMLPorps包更好!!!  
   
  example   of   usage:    
   
    xml   file:  
     
    <root>  
        <user>  
              <name>Tomas</name>  
              <age   year="1978"/>  
        </user>  
    </root>  
   
    XMLProps   xmlp   =   new   XMLProps("file.xml");  
    String   name   =   xmlp.getProperty("user.name");  
    String   age   =   xmlp.getPropertyAttribute("user.age","year");  
   
  ×××××××××  
    name   will   be   set   Tomas  
    age   will   be   set   1978  
     
  是不是和你的要求一样   !!!!!!!!!!!!!!!!!!!  
   
  google   XMLProps         start   ..........  
   
  -----------------  
  有一种目光,总在分手时,才看见是眷恋.  
  有一种心情,总在离别后,才明白是失落.  
  有一种感觉,总在难眠时,才承认是相思.  
  有一种缘份,总在梦醒后,才相信是永恒.  
  -----------------  
  Top

7 楼fengyuxi(koala)回复于 2002-08-13 13:32:17 得分 0

XMLPorps包在那里有下载?  
  是个什么样的项目,归哪个组织管啊?Top

相关问题

  • 谁给个用JDOM创建新的XML文档的例子吧!100分
  • dom4j写xml文档的例子的傻瓜问题
  • 谁能给一个向xml文档中插入数据的例子?
  • 求例子/方法:jsp/servlet 读取xml文档里面的数据
  • 请教,如何使用JDOM操作XML文档?
  • JDOM建立XML文档时如何修改encoding的属性?
  • 可以用SQL语句对XML文档进行查询吗?如果可以,给个例子看看好吗?
  • 谁能给我一些用xerces_j解析xml文档的例子,越多越好
  • 有没有将一个XML文档转换为一棵JTree显示的例子,拜托拜托!
  • 请问,如何用JDOM打开一个有schema验证的xml文档。

关键词

  • w3c
  • 文件
  • 文档
  • jdom
  • currentelement
  • parameterchildlist
  • childlist
  • getchild
  • queryparametername
  • parametername

得分解答快速导航

  • 帖主:fengyuxi
  • binriyue
  • soldier1002
  • Dickensi
  • demonangel

相关链接

  • CSDN Java频道
  • Java类图书
  • Java类源码下载

广告也精彩

反馈

请通过下述方式给我们反馈
反馈
提问
网站简介|广告服务|VIP资费标准|银行汇款帐号|网站地图|帮助|联系方式|诚聘英才|English|问题报告
北京创新乐知广告有限公司 版权所有, 京 ICP 证 070598 号
世纪乐知(北京)网络技术有限公司 提供技术支持
Copyright © 2000-2008, CSDN.NET, All Rights Reserved
GongshangLogo