在前面的示例中,您可以看到如何将bean转换为XML持久性。现在我们做相反的事情,将XML转换回bean。对于BeanToXML此示例中使用的类,请参阅如何将bean转换为XML持久性?例。
package org.nhooo.example.bean; import java.beans.XMLDecoder; import java.io.BufferedInputStream; public class XmlToBean { public static void main(String[] args) { XMLDecoder decoder = new XMLDecoder(new BufferedInputStream( XmlToBean.class.getResourceAsStream("Bean.xml"))); // 从基础输入流中读取下一个对象。 BeanToXML bean = (BeanToXML) decoder.readObject(); decoder.close(); System.out.println("ID = " + bean.getId()); System.out.println("Item Name = " + bean.getItemName()); System.out.println("Item Colour = " + bean.getItemColour()); System.out.println("Item Quantities = " + bean.getItemQuantities()); } }
这是我们的Bean.xml持久性文件:
<?xml version="1.0" encoding="UTF-8"?> <java version="1.6.0_02"> <object> <void property="id"> <long>1</long> </void> <void property="itemColour"> <string>Dark Red</string> </void> <void property="itemName"> <string>T-Shirt</string> </void> <void property="itemQuantities"> <int>100</int> </void> </object> </java>
结果是:
ID = 1Item Name = T-ShirtItem Colour = Dark RedItem Quantities = 100