最近学习的XML。

   由于公司有个项目需要XML,主要时将Access中的符合条件的数据生成XML文件,以为程序所用。所以就上网上看了一下,关于XML的还真多啊,JDOM,DOM4J。我下的是最新的JDOM1.0,DOM4J1.6.1,网上的一些例子是原来版本的,所以需要改进一下。

  一、JDOM1.0的例子:CreateXMLtest,FibonacciJDOM,DataToXML(自己写的操作SQLServer2000的,没有完成,老是报错啊java.lang.ClassCastException ,希望能有高手解决) 

    1、CreateXMLtest示例

package com.sengle;

import java.io.*;
import org.jdom.Attribute;
import org.jdom.Comment;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

public class CreateXMLtest {
 public void createxml(){
 Element root = new Element("ResultSet");
 Document doc = new Document(root);
 
 
 Element row = new Element("Row");
 Element column = new Element("colName");
 column.setAttribute("type","colType");
 column.setText("colValue".trim());
 row.addContent("column");
 root.addContent(row);
 

 try {
 XMLOutputter outputter = new XMLOutputter();//(" ",true);
 FileWriter writer = new FileWriter(".//myFile1.xml");
 System.out.println("现在正在生成XML文件,请稍等...");
 outputter.setFormat(Format.getPrettyFormat().setEncoding("GB2312"));
 outputter.output(doc,writer);
 writer.close();
 System.out.println("XML文件已生成.");
 }
 catch(java.io.IOException e) {
 e.printStackTrace();
 }
 }
 public static void main(String[] args){
  try{
   CreateXMLtest test1=new CreateXMLtest();  
   test1.createxml();
  }catch(Exception e){
   System.out.println(e.getMessage());
  }
  
 }

}

   2、FibonacciJDOM ,生成Fibonacci数

package com.sengle;
import org.jdom.*;
import org.jdom.output.XMLOutputter;
import org.jdom.output.Format;
import java.math.BigInteger;
import java.io.IOException;

public class FibonacciJDOM {
 public static void main(String[] args) {

     Element root = new Element("Fibonacci_Numbers");

     BigInteger low  = BigInteger.ONE;
     BigInteger high = BigInteger.ONE;

     for (int i = 1; i <= 5; i++) {
       Element fibonacci = new Element("fibonacci");
       fibonacci.setAttribute("index", String.valueOf(i));
       fibonacci.setText(low.toString());
       root.addContent(fibonacci);

       BigInteger temp = high;
       high = high.add(low);
       low = temp;
     }

     Document doc = new Document(root);
     // serialize it onto System.out
     try {
       XMLOutputter serializer = new XMLOutputter();
     
       serializer.setFormat(Format.getPrettyFormat());
       serializer.setFormat(Format.getPrettyFormat().setEncoding("GB2312"));
       serializer.output(doc, System.out);
     }
     catch (IOException e) {
       System.err.println(e);
     }

   }

}
   3、数据转换XML,有问题的程序,希望解决

package com.sengle;

import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import java.sql.*;
public class DataToXML {
 static String url="****";//URL
 static String username="***";//数据库用户名
 static String password="***";//密码
 static Connection conn;
 static Statement state;
 static ResultSet rs;
 static List lst=new ArrayList();
 
 
 public static void main(String[] args) throws IOException, SQLException{
  
  FileWriter writer = new FileWriter(".//DataToXML.xml");
  lst=getData(); 
  //convert(lst,writer);
  convert(lst,System.out);
 }

 public static List getData() throws SQLException {
  try{
   Class.forName("net.sourceforge.jtds.jdbc.Driver");
   conn=DriverManager.getConnection(url,username,password);
   
   String queryStr="select * from baidu_records";
   System.out.println("处理完数据查询...");
   state=conn.createStatement();
   rs=state.executeQuery(queryStr);
   while(rs.next()){
    lst.add(rs.getString(7));
   }
   
  }catch(ClassNotFoundException e){
   System.out.println("加载数据库驱动失败.");
   e.printStackTrace();
   System.exit(1);
  }
  return lst;
 }

 private static void convert(List data, FileWriter writer) throws IOException{
  
        Element budget = new Element("Budget");
       
     Iterator records = data.iterator();
     while (records.hasNext()) {
       Element lineItem = new Element("LineItem");
       budget.addContent(lineItem);
      
       Map record = (Map) records.next();
       Set fields = record.entrySet();
       Iterator entries = fields.iterator();
       while (entries.hasNext()) {
         Map.Entry entry = (Map.Entry) entries.next();
         String name = (String) entry.getKey();
         String value = (String) entry.getValue();
        
         Element category = new Element(name);
         category.setText(value);
         lineItem.addContent(category);
       }
     }

     Document doc = new Document(budget);
     XMLOutputter outputter = new XMLOutputter();
     outputter.setFormat(Format.getPrettyFormat());
     outputter.output(doc, writer);
     writer.close();
 }

 private static void convert(List data, OutputStream out) throws IOException{
  
  Element budget = new Element("Budget");
       
     Iterator records = data.iterator();
     while (records.hasNext()) {
       Element lineItem = new Element("LineItem");
       budget.addContent(lineItem);
      
       Map record = (Map) records.next();//此处报错java.lang.ClassCastException 
       Set fields = record.entrySet();
       Iterator entries = fields.iterator();
       while (entries.hasNext()) {
         Map.Entry entry = (Map.Entry) entries.next();
         String name = (String) entry.getKey();
         String value = (String) entry.getValue();
        
         Element category = new Element(name);
         category.setText(value);
         lineItem.addContent(category);
       }
     }

     Document doc = new Document(budget);
     XMLOutputter outputter = new XMLOutputter();
     outputter.setFormat(Format.getPrettyFormat());
     outputter.output(doc, out);
     out.flush();
        
 }

}

二、DOM4J1.6.1 Quick Start例子改写,Foo.java

package com.sengle.dom4j;
import java.io.FileWriter;
import java.io.IOException;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

public class Foo {
 public Document createDocument() throws IOException {
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement( "root" );

        Element author1 = root.addElement( "author" )
            .addAttribute( "name", "James" )
            .addAttribute( "location", "UK" )
            .addText( "James Strachan" );
       
        Element author2 = root.addElement( "author" )
            .addAttribute( "name", "Bob" )
            .addAttribute( "location", "US" )
            .addText( "Bob McWhirter" );
       
        return document;
    }
 public void write(Document document) throws IOException {

        // lets write to a file
        XMLWriter writer = new XMLWriter(
            new FileWriter( "output.xml" )
        );
        //writer.write( document );
        //writer.close();


        // Pretty print the document to System.out
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("GB2312");
        writer = new XMLWriter( System.out, format );
        writer = new XMLWriter(new FileWriter( "output.xml" ),format);
        writer.write( document );
        writer.close();
/*
        // Compact format to System.out
        format = OutputFormat.createCompactFormat();
        format.setEncoding("GB2312");
        writer = new XMLWriter( System.out, format );
        writer.write( document );*/
    }

 public static void main(String[] args) throws IOException{
  Foo foo=new Foo();
  Document doc=foo.createDocument();
  foo.write(doc);
 }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值