XStream解析XML学习一

前端之家收集整理的这篇文章主要介绍了XStream解析XML学习一前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这个例子是参照官网上面的例子写的: http://xstream.codehaus.org/tutorial.html

1.首先构造想要序列化的类

Person.java:

[java] view plain copy
  1. publicclassPerson{
  2. privateStringfirstname;
  3. privateStringlastname;
  4. privatePhoneNumberphone;
  5. privatePhoneNumberfax;
  6. //...constructorsandmethods
  7. publicPerson(Stringfirstname,Stringlastname){
  8. super();
  9. this.firstname=firstname;
  10. this.lastname=lastname;
  11. }
  12. voidsetPhone(PhoneNumberphoneNumber){
  13. this.phone=phoneNumber;
  14. }
  15. voidsetFax(PhoneNumberphoneNumber){
  16. this.fax=phoneNumber;
  17. @Override
  18. publicStringtoString(){
  19. return"FirstName:"+firstname+",LastName:"+lastname
  20. +"phone.Code:"+phone.getCode()+"phone.Number:"
  21. +phone.getNumber()+"fax:"+fax.getCode()+"fax.Number:"
  22. +fax.getNumber();
  23. }

PhoneNumber.java:

copy
    classPhoneNumber{
  1. privateintcode;
  2. privateStringnumber;
  3. publicPhoneNumber(intcode,Stringnumber){
  4. this.code=code;
  5. this.number=number;
  6. intgetCode(){
  7. returncode;
  8. publicStringgetNumber(){
  9. returnnumber;
  10. }

2.初始化XStream并序列化和反序列化。

StreamxStream=newXStream();

你需要xstream-[version].jar and xpp3-[version].jar在classpath中。XPP3是一个非常快的XML拉式转换器工具。如果你不想包含这个依赖,你可以使用标准的JAXP DOM转换器来代替。

XStream xStream = new XStream(new DomDriver());//不需要XPP3库

这里要特别说明的是XStream xStream2=new XStream();这样会出错,使用原来的

copy
    classXStreamTest{
  1. staticvoidmain(String[]args)throwsFileNotFoundException{
  2. //InitializingXStream
  3. XStreamxStream=newXStream();
  4. xStream.alias("person",Person.class);
  5. xStream.alias("personnumber",PhoneNumber.class);
  6. //SerializinganobjecttoXML
  7. Personjoe=newPerson("Joe","Walnes");
  8. joe.setPhone(newPhoneNumber(123,"1234-456"));
  9. joe.setFax("9999-999"));
  10. FileOutputStreamfileOutputStream=newFileOutputStream(newFile("test.xml"));
  11. xStream.toXML(joe,fileOutputStream);
  12. //DeserializinganobjectbackfromXM
  13. XStreamxStream2= FileInputStreamfileInputStream=newFileInputStream(newFile("test.xml"));
  14. Personperson=(Person)xStream.fromXML(fileInputStream);
  15. System.out.println(person.toString());
  16. }

看一下运行的结果:

test.xml:

[xhtml] copy
    <person>
  1. firstname>Joe</>
  2. lastname>Walnesphonecode>123number>1234-456fax>9999-999>
原文链接:https://www.f2er.com/xml/299031.html

猜你在找的XML相关文章