jdom学习(5)

Jdom使用详解及实例(5)
接上一节:

6、数据输入要用到XML文档要通过org.jdom.input包,反过来需要org.jdom.output。如前面所说,关是看API文档就能够使用。

我们的例子读入XML文件exampleA.xml,加入一条处理指令,修改第一本书的价格和作者,并添加一条属性,然后写入文件exampleB.xml

//exampleA.xml

xml 代码
xml version="1.0" encoding="GBK"?>      <bookList>      <book>      <name>Java编程入门name>      <author>张三author>      <publishDate>2002-6-6publishDate>      <price>35.0price>      book>      <book>      <name>XML在Java中的应用name>      <author>李四author>      <publishDate>2002-9-16publishDate>      <price>92.0price>      book>      bookList>   
//testJDOM.java

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 代码
  1. xml version="1.0" encoding="GBK"?>  
  2. <bookList>  
  3. <book hot=”true”>  
  4. <name>Java编程入门name>  
  5. <author>50.0author>  
  6. <publishDate>2002-6-6publishDate>  
  7. <price>35.0price>  
  8. book>  
  9. <book>  
  10. <name>XML在Java中的应用name>  
  11. <author>李四author>  
  12. <publishDate>2002-9-16publishDate>  
  13. <price>92.0price>  
  14. book>  
  15. bookList>  
  16. xml-stylesheet href="bookList.html.xsl" type="text/xsl"?>   

在默认情况下,JDOMElement类的getText()这类的方法不会过滤空白字符,如果你需要过滤,用setTextTrim()


注:以上内容引用自网上资料http://blog.csdn.net/vb1088blog/

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值