如何将xml文件转变成java对象

Python09

如何将xml文件转变成java对象,第1张

首先 java是面向对象的编程语言,所以你要理解面向对象的思想。在这个前提下我们可以理解 文件 本身就是java的对象File,而xml只是File类中对象的一种实例。你可以创建一个File 把你的xml的路径传入这个对象的有参构造,这样就实例化了一个xml文件类的对象

SAXBuilder sb = new SAXBuilder()//建立构造器  

        Document doc

        try {

            doc = sb.build("E:/userinfod301.xml") //读入指定文件

            Element root = doc.getRootElement()//获得根节点  

            List list = root.getChildren()//将根节点下的所有ObjectInstance子节点放入List中  

            for (int i = 0 i < list.size() i++) {

                List<Element> listNext = ((Element) list.get(i)).getChildren()//将ObjectInstance节点下的所有Attribute放入List中  

                for (int j = 0 j < listNext.size() j++) {

                    Element sub = (Element) listNext.get(j)//取得节点实例  

                    System.out.println(sub.getAttribute("name").getValue())

                    System.out.println(sub.getText())

                }

            }

        } catch (Exception e) {

            e.printStackTrace()

        }

import java.beans.XMLDecoder

import java.beans.XMLEncoder

import java.io.BufferedInputStream

import java.io.BufferedOutputStream

import java.io.File

import java.io.FileInputStream

import java.io.FileNotFoundException

import java.io.FileOutputStream

import java.io.IOException

public class Object2XML {

public static String object2XML(Object obj, String outFileName)

throws FileNotFoundException {

// 构造输出XML文件的字节输出流

File outFile = new File(outFileName)

BufferedOutputStream bos = new BufferedOutputStream(

new FileOutputStream(outFile))

// 构造一个XML编码器

XMLEncoder xmlEncoder = new XMLEncoder(bos)

// 使用XML编码器写对象

xmlEncoder.writeObject(obj)

// 关闭编码器

xmlEncoder.close()

return outFile.getAbsolutePath()

}

public static Object xml2Object(String inFileName)

throws FileNotFoundException {

// 构造输入的XML文件的字节输入流

BufferedInputStream bis = new BufferedInputStream(

new FileInputStream(inFileName))

// 构造一个XML解码器

XMLDecoder xmlDecoder = new XMLDecoder(bis)

// 使用XML解码器读对象

Object obj = xmlDecoder.readObject()

// 关闭解码器

xmlDecoder.close()

return obj

}

public static void main(String[] args) throws IOException {

// 构造一个StudentBean对象

StudentBean student = new StudentBean()

student.setName("wamgwu")

student.setGender("male")

student.setAge(15)

student.setPhone("55556666")

// 将StudentBean对象写到XML文件

String fileName = "AStudent.xml"

Object2XML.object2XML(student, fileName)

// 从XML文件读StudentBean对象

StudentBean aStudent = (StudentBean)Object2XML.xml2Object(fileName)

// 输出读到的对象

System.out.println(aStudent.toString())

}

}