java xml学习(二)

本文详细介绍了如何使用XStream库将Java对象转换为XML格式,并展示了如何存储多个对象到XML文件中。包括代码示例、XML文件格式解析以及从XML文件读取对象的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    对于上一篇提到的创建xml的方式,需要创建节点比较麻烦,另外还有一种方式是直接将对象类转换成xml文件,这就需要用到XStream

    代码示例如下:

     person p = new person();
     p.setName123");
     p.setFlex("girl");
     p.setAge(15);
     XStream stream = new XStream(new DomDriver());
    String ps  = stream.toXML(p);

    需要建立person类 引入XSream JAR包

    今天又深入的看了一下 ,之前的理解还有不正确的地方,如果想存储多个对象,也是可以做到的,不过采取的方式就需要使用map表了

代码如下:

Map<String, person> persons = new HashMap<String, person>();
  person p = new person();
  
 p.setName123");
 p.setFlex("girl");
  p.setAge(15);
  person p1 = new person();
  p1.setName("q");
  p1.setFlex("girl");
  p1.setAge(18);
  persons.put(p.getName(), p);
  persons.put(p1.getName(), p1);
  XStream stream = new XStream(new DomDriver());
  String ps  = stream.toXML(persons);
  System.out.println(ps);
  String rootDir = System.getProperty("user.dir");
  File file = new File(rootDir+"//person.xml");
  FileOutputStream fo = new FileOutputStream(file);
  byte [] b = new byte[1024];
  ByteArrayInputStream bt = new ByteArrayInputStream(ps.getBytes());
  while(bt.read(b) > -1){
   fo.write(b);
  }
  return ps;

这样就可以存储多个对象了,xml格式如下:

读取文件的时候和这个类似:

public void readXml() throws FileNotFoundException{
  Map<String, person> persons = new HashMap<String, person>();
  try {
   XStream xstream = new XStream(new DomDriver("utf-8"));
   File xmlFile = new File("D:\\Workspaces\\MyEclipse 8.5\\qq\\java261\\person.xml");
   if (!xmlFile.exists())
    return;
   FileInputStream fos = new FileInputStream(xmlFile);
   xstream.omitField(person.class, "enabled");
   Object o = xstream.fromXML(fos);
   if (!(o instanceof Map<?,?>)) {
    return;
   }
   persons = ((Map) o);
   for(person p :persons.values()){
    System.out.println(p.getName());
   }
   fos.close(); 
   xmlFile = null;
  } catch (Exception e) {
   // TODO: handle exception
  }
 }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值