使用xmlbeans构造符合相应Schema格式的xml文件

接着上例的 automobile-policy.xsd


      
    
    
    
    
    
      
   
   
   
     
    
   
   
   
     
    
   
     
    
   
     
 



 

确保该schema文件已经使用scomp编译过,并将生成的jar包导入到了工程中,且工程中加入了xmlbeans的jar文件

新建源文件:

import java.io.File;
import java.util.Calendar;
import java.util.Date;
import org.apache.xmlbeans.XmlOptions;
import noNamespace.*;
public class createXml {
 public static void main(String args[]){
  File out=new File("src/out.xml");
  Calendar date=Calendar.getInstance();
  date.setTime(new Date());
  
  AutomobilePolicyDocument autoPolicyDoc=AutomobilePolicyDocument.Factory.newInstance();
  autoPolicyDoc.addNewAutomobilePolicy();
  AutomobilePolicyDocument.AutomobilePolicy autoPolicyElement=autoPolicyDoc.getAutomobilePolicy();
  
  autoPolicyElement.setInsuranceDate(date);
  
  autoPolicyElement.addNewInsuredVehicle();
  InsuredVehicle insuredVehile=InsuredVehicle.Factory.newInstance();
  insuredVehile.setYearOfManufacture("2011");
  insuredVehile.setMake("XUPT");
  insuredVehile.setModel("Optra");
  insuredVehile.setPrice(1234);
  autoPolicyElement.setInsuredVehicle(insuredVehile);
  
  autoPolicyElement.addNewLiabilityCoverage();
  LiabilityCoverage liabilityCoverage=LiabilityCoverage.Factory.newInstance();
  liabilityCoverage.setCoverageLimit(123456);
  liabilityCoverage.setCoveragePremium(654321);
  autoPolicyElement.setLiabilityCoverage(liabilityCoverage);
  
  autoPolicyElement.addNewPolicyholderInformation();
  PolicyholderInformation policyholderInformation=PolicyholderInformation.Factory.newInstance();
  policyholderInformation.setName("Adam");
  policyholderInformation.setSocialSecurityNumber("1GBL7D1G3GV100770");
  policyholderInformation.setAddress("Bell's Tower");
  autoPolicyElement.setPolicyholderInformation(policyholderInformation);
  
  autoPolicyElement.addNewThirdPartyCoverage();
  ThirdPartyCoverage thirdPartyCoverage=ThirdPartyCoverage.Factory.newInstance();
  thirdPartyCoverage.setCoverageLimit(2222);
  thirdPartyCoverage.setCoveragePremium(3333);
  autoPolicyElement.setThirdPartyCoverage(thirdPartyCoverage);
  
  
  autoPolicyDoc.documentProperties().setEncoding("UTF-8");
  autoPolicyDoc.documentProperties().setVersion("1.0");
  
  System.out.print(autoPolicyDoc.xmlText(new XmlOptions().setSavePrettyPrint()));
  try{
   autoPolicyDoc.save(out, new XmlOptions().setSavePrettyPrint());
  }catch(Exception e){
   e.printStackTrace();
  }
 }
}


 

这样就按照指定的xsd文件生成了一个out.xml文件其内容如下:



  2011-10-24T16:03:18.546+08:00
  
    Adam
    1GBL7D1G3GV100770
    
Bell's Tower
2011 XUPT Optra 1234.0 123456.0 654321.0 2222.0 3333.0

你可能感兴趣的:(xmlbeans)