谁做过读取txt文本,txt文本里面是xml格式的,通过对象的形式读取出来

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




然后读取的Student对象的数据

[code="java"]
package test;

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class Test {

/**
 * 对象=〉XML
 * @param xmlFile
 * @param obj
 * @throws Exception
 */
public static void writeObjectToXML(File xmlFile, Object obj) throws Exception {
    XMLEncoder xmlEncoder = null;
    try {
        xmlEncoder = new XMLEncoder(new FileOutputStream(xmlFile));
        xmlEncoder.writeObject(obj);
    } finally {
        if (null != xmlEncoder)
            xmlEncoder.close();
    }
}

/**
 * XML=〉对象
 * @param xmlFile
 * @throws Exception
 */
public static Object readObjectFromXML(File xmlFile) throws Exception {
    XMLDecoder xmlDecoder = null;

    try{
        xmlDecoder = new XMLDecoder(new FileInputStream(xmlFile));
        return xmlDecoder.readObject();
    }finally{
        if(null != xmlDecoder)
            xmlDecoder.close();
    }
}

public static void main(String[] args) {

    User user = new User();
    user.setId(1);
    user.setName("zhangsan");

    try {
        writeObjectToXML(new File("xml.txt"), user);

        User u = (User)readObjectFromXML(new File("xml.txt"));
        System.out.println(u.getId() + "\t" + u.getName());
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

}

[/code]

xml.txt

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



1


zhangsan


自己google下 java xml

可以采用XML SAX的方式,以流的形式读取出来。 自行解析这件事情比较复杂。

另外看题主的数据格式呢,貌似使用java.beans.XMLDecoder也可以读取出来,这样直接就变成一个Bean了,试试看。

xstream 或者 jackson肯定能够满足你的需求

Jaxb,jdk自身带的框架就支持的

你这不是XML读取数据 而是OI方面的问题 除非你先把文件转化成xml文件 然后用XML 解析
IO 代码如下(随手写了一下 不对请指出):

package cn.com.wangxiuwei.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;

import cn.com.wangxiuwei.entity.Student;

public class TestXml {

/**
 * @param args
 * @throws IOException 
 * @throws ClassNotFoundException 
 */
public static void main(String[] args) throws IOException, ClassNotFoundException {


    File file=new File("F:"+File.separator+"test.txt");
    OutputStream os=new FileOutputStream(file);

    ObjectOutputStream oos=new ObjectOutputStream(os);

    Student s=new Student();
    s.setId(1);
    s.setName("dd");

    oos.writeObject(s);
    oos.close();
    os.close();

    InputStream is= new FileInputStream(file);
    ObjectInputStream ois=new ObjectInputStream(is);
    Student student=(Student)ois.readObject();
    System.out.println(student.getId()+"  "+ student.getName());
    ois.close();
    is.close();





}

}