jibx的helloworld

参考http://jibx.sourceforge.net/fromcode/bindgen-example1.html
下载jibx_1_2_3.zip
进入example/bindgen例子
现象就是,根据xml生成bean,操作算出总金额后,之后又转换回xml,可以比较下和xml有什么不同。
其实就是bean,生成转换文件,xml--->bean--->xml
步骤:
1.根据javabean生成class
2.更具class生成binding.xml和xsd,为bean生成xml提供基础
3.bind,根据binding.xml和xsd生成jibx的class(factory,adapter,bean对应等)
4.根据xml生成bean对象,操作完之后,还能把bean对象转换成xml

使用ant
build.xml说明:
target----->full分解一下
1.compile-----编译
    Address.java
    Customer.java
    Item.java
    Order.java
    Shipping.java
    主要是Order.java,其他类在order中
2.custgen1----->custgen
    生成bingding.xml和starter1.xsd
用来进行转换的
3.bind
    生成jibx的类
4.test
Test.java里面这样写的
package org.jibx.starter1;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Iterator;
import org.jibx.runtime.BindingDirectory;
import org.jibx.runtime.IBindingFactory;
import org.jibx.runtime.IMarshallingContext;
import org.jibx.runtime.IUnmarshallingContext;
import org.jibx.runtime.JiBXException;
public class Test
{
	/*第一个参数是输入的xml ,第二个参数是输出的xml*/
	public static void main(String[] args) {
        if (args.length < 2) {
            System.out.println("Usage: java -cp ... " + "org.jibx.starter1.Test in-file out-file");
            System.exit(0);
        }
		try {
            // unmarshal customer information from file
            IBindingFactory bfact = BindingDirectory.getFactory(Order.class);
            IUnmarshallingContext uctx = bfact.createUnmarshallingContext();
            FileInputStream in = new FileInputStream(args[0]);
            Order order = (Order)uctx.unmarshalDocument(in, null);//Unmarshal是将xml文件转换成java对象
            // compute the total amount of the order
            float total = 0.0f;
            for (Iterator<Item> iter = order.getItems().iterator(); iter.hasNext();) {
                Item item = iter.next();
                total += item.getPrice() * item.getQuantity();
            }
            order.setTotal(new Float(total));//把bean处理了一下
			// marshal object back out to file (with nice indentation, as UTF-8)
			IMarshallingContext mctx = bfact.createMarshallingContext();
			mctx.setIndent(2);
			FileOutputStream out = new FileOutputStream(args[1]);
			mctx.setOutput(out, null);
			mctx.marshalDocument(order);//把java对象转换成xml文件
			System.out.println("Unmarshalled and marshalled order with " + order.getItems().size() + " items and total value " + total);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
            System.exit(1);
		} catch (JiBXException e) {
			e.printStackTrace();
            System.exit(1);
		}
	}
}

你可能感兴趣的:(java,bean,.net,xml,ant)