|
| 1 | +package com.hmkcode; |
| 2 | + |
| 3 | +import java.io.FileReader; |
| 4 | +import java.io.FileWriter; |
| 5 | +import java.io.IOException; |
| 6 | +import java.io.Reader; |
| 7 | +import java.io.Writer; |
| 8 | + |
| 9 | +import org.exolab.castor.mapping.Mapping; |
| 10 | +import org.exolab.castor.mapping.MappingException; |
| 11 | +import org.exolab.castor.xml.MarshalException; |
| 12 | +import org.exolab.castor.xml.Marshaller; |
| 13 | +import org.exolab.castor.xml.Unmarshaller; |
| 14 | +import org.exolab.castor.xml.ValidationException; |
| 15 | +import org.exolab.castor.xml.XMLContext; |
| 16 | + |
| 17 | +import com.hmkcode.vo.Article; |
| 18 | + |
| 19 | + |
| 20 | +public class AppMapping |
| 21 | +{ |
| 22 | + public static void main( String[] args ) |
| 23 | + { |
| 24 | + |
| 25 | + try { |
| 26 | + //Load Mapping |
| 27 | + Mapping mapping = new Mapping(); |
| 28 | + mapping.loadMapping("mapping.xml"); |
| 29 | + XMLContext context = new XMLContext(); |
| 30 | + context.addMapping(mapping); |
| 31 | + |
| 32 | + //( 1 ) OBJECT --> XML |
| 33 | + |
| 34 | + //1.1 Prepare file writer |
| 35 | + Writer writer = new FileWriter("mapped_article.xml"); |
| 36 | + |
| 37 | + //1.2 Create a new Marshaller |
| 38 | + Marshaller marshaller = context.createMarshaller(); |
| 39 | + marshaller.setWriter(writer); |
| 40 | + |
| 41 | + //1.3 Marshal "map" to xml |
| 42 | + marshaller.marshal(createArticle()); |
| 43 | + |
| 44 | + //1.4 |
| 45 | + writer.close(); |
| 46 | + |
| 47 | + |
| 48 | + //( 2 ) XML --> OBJECT |
| 49 | + |
| 50 | + //2.1 Prepare file writer |
| 51 | + Reader reader = new FileReader("mapped_article.xml"); |
| 52 | + |
| 53 | + //2.2 Create a new Unmarshaller |
| 54 | + Unmarshaller unmarshaller = context.createUnmarshaller(); |
| 55 | + unmarshaller.setClass(Article.class); |
| 56 | + |
| 57 | + //2.3 Unmarshal "map" to Object |
| 58 | + Article article = (Article) unmarshaller.unmarshal(reader); |
| 59 | + |
| 60 | + //2.4 |
| 61 | + reader.close(); |
| 62 | + |
| 63 | + System.out.println(article); |
| 64 | + |
| 65 | + } catch (IOException e1) { |
| 66 | + e1.printStackTrace(); |
| 67 | + } catch (MappingException e1) { |
| 68 | + e1.printStackTrace(); |
| 69 | + } catch (MarshalException e) { |
| 70 | + e.printStackTrace(); |
| 71 | + } catch (ValidationException e) { |
| 72 | + e.printStackTrace(); |
| 73 | + } |
| 74 | + } |
| 75 | + public static Article createArticle(){ |
| 76 | + Article article = new Article(); |
| 77 | + |
| 78 | + article.setTitle("Castor - Java Object to XML & XML to Object Mapping"); |
| 79 | + article.setUrl("http://hmkcode.com/castor-java-object-xml"); |
| 80 | + article.addCategory("Java"); |
| 81 | + article.addTag("Java"); |
| 82 | + article.addTag("Castor"); |
| 83 | + article.addTag("XML"); |
| 84 | + article.addTag("Marshalling"); |
| 85 | + article.addTag("Unmarshalling"); |
| 86 | + |
| 87 | + return article; |
| 88 | + } |
| 89 | +} |
0 commit comments