Help in jxls reader - apache-poi

HI
I am new to jxls. I read the articles regarding it, but seems not so good examples there. I am reading a xls file through java.
Please find the simple attached xls file for the same.
1)
public class Employee {
private String rollno;
private String name;
private String percentage;
2)
<worksheet name="Sheet1">
<section endRow="1" startRow="0"/>
<loop endRow="4" items="employee" startRow="3" var="emp" varType="com.Employee">
<section endRow="4" startRow="3">
<mapping col="0" row="3">emp.rollno</mapping>
<mapping col="1" row="3">emp.name</mapping>
<mapping col="2" row="3">emp.percentage</mapping>
</section>
</loop>
</worksheet>
3)
public class Client {
public static void main(String[] args) throws IOException, SAXException {
InputStream inputXML = new BufferedInputStream(new FileInputStream("C:\\NewFile1.xml"));
XLSReader mainReader = ReaderBuilder.buildFromXML( inputXML );
InputStream inputXLS = new BufferedInputStream(new FileInputStream("c:\\Book1.xls"));
Employee employee = new Employee();
System.out.println("Is Null inputXML:"+inputXML==null);
System.out.println("Is Null inputXLS:"+inputXLS==null);
Map beans = new HashMap();
beans.put("employee", employee);
XLSReadStatus readStatus = mainReader.read( inputXLS, beans);
readStatus.toString();
}
}
I am getting a exception as
Feb 21, 2011 3:59:17 PM net.sf.jxls.reader.XLSReaderImpl readSheet
INFO: Processing sheet Sheet1
Exception in thread "main" java.lang.NullPointerException
at net.sf.jxls.reader.XLSForEachBlockReaderImpl.read(XLSForEachBlockReaderImpl.java:45)
at net.sf.jxls.reader.XLSSheetReaderImpl.read(XLSSheetReaderImpl.java:25)
at net.sf.jxls.reader.XLSReaderImpl.readSheet(XLSReaderImpl.java:45)
at net.sf.jxls.reader.XLSReaderImpl.read(XLSReaderImpl.java:31)
at com.GetTheData.main(GetTheData.java:41)
Please help in solving this prob.
Thank you

You need to define a loopbreakcondition to stop the loop iteration based on some condition.
For example:
<worksheet name="Sheet1">
<section endRow="1" startRow="0"/>
<loop endRow="4" items="employee" startRow="3" var="emp" varType="com.Employee">
<section endRow="4" startRow="3">
<mapping col="0" row="3">emp.rollno</mapping>
<mapping col="1" row="3">emp.name</mapping>
<mapping col="2" row="3">emp.percentage</mapping>
</section>
<loopbreakcondition>
<rowcheck offset="0">
<cellcheck offset="0">END</cellcheck>
</rowcheck>
</loopbreakcondition>
</loop>
</worksheet>
Take a look at the user guide for more information.

Client.java this line : beans.put("employee", employee);
change to :
beans.put("employee", new ArrayList() );
works for me.

Related

Posting an array of string

I am trying to post a string array to the post action in an Razor Pages project. For this, I thought about using a hidden <select> tag. The user would enter text into a text box, press a button and I would then add a new option to the <select> then post the whole thing with a submit button. However, after everything is posted, the array property of my model is empty.
Does anyone know if there is a better way of doing this or what I am doing wrong?
Razor:
<form method="post">
<input id="string-value" />
<input type="button" id="add-item" value="Add item" />
<select asp-items="#Model.Model.ArrayOfStrings" id="hidden-select"></select>
<table id="table-items">
</table>
<input type="submit" value="Submit" />
</form>
public class ArrayModel
{
public List<SelectListItem> ArrayOfStrings { get; set; } = new List<SelectListItem>();
}
public class IndexModel : PageModel
{
[BindProperty]
public ArrayModel Model { get; set; }
public void OnGet()
{
Model = new ArrayModel();
}
public void OnPost()
{
System.Diagnostics.Debugger.Break();
}
}
JS:
$('#add-item').on('click', function () {
debugger;
var value = $('#string-value').val();
$('#hidden-select').append(new Option(value, value));
$('#table-item tr:last').after('<tr><td>' + value + '</td></tr>')
});
Repository can be found here.
The options of the select will not be posted so this will not work.
The easiest way to do this is append the results to a hidden input with a separator char, then do a string split on the server side.
Another, maybee more elegant way, would be to add hidden inputs with the same name. Each input with it's own value. You should then be able to get this as a List or Array on the server.
Razor:
<input value="#String.Join(",", Model.Model.ArrayOfStrings)" id="tags"></select>
JS
$('#tags').val($('#tags').val() + ',' + value);
Controller
public void OnPost(string tags)
{
var tagsArray = tags.split(',');
}

Not able to generate Excel file correctly using Spring Boot and Apache POI

I have a very basic SpringBoot and Thymeleaf based application that is tied with Oracle DB.
My application currently reads from a table and displays it on the page via a Controller and Thymeleaf UI template. I also have a link at the bottom of this table which says "Export to Excel" which calls a method in service layer and generates and even downloads that .XLS document successfully.
However, the problem is that the excel getting generated is an exact replica of what is on the page (with some extra empty columns on the right) even though I have created the sheet manually by writing code which adds an extra column and a different title.
Not sure why isn't my code getting invoked and why is my HTML table data just getting exported to the excel sheet as is.
ExcelReportController.java
#Controller
#Log4j2
public class ExcelReportController {
private static final String EXCEL_FILE_NAME = "applications.xls";
#Autowired
private LinkApplService linkApplService;
#GetMapping("/excel")
public ModelAndView showPage() {
return new ModelAndView("applications", "linkAppls", linkApplService.getAllLinkAppls());
}
#GetMapping("/download")
public ModelAndView download(HttpServletResponse response) {
response.setHeader("Content-disposition", "attachment; filename=" + EXCEL_FILE_NAME);
return new ModelAndView("applications", "linkAppls", linkApplService.getAllLinkAppls());
}
}
ExcelBuilderService.java
#Service
public class ExcelBuilderService extends AbstractXlsView {
#Override
protected void buildExcelDocument(Map<String, Object> model, Workbook workbook, HttpServletRequest request,
HttpServletResponse response) {
Iterable<LinkAppl> linkAppls = (Iterable<LinkAppl>) model.get("linkAppls");
//THIS SHEET WITH TITLE NOT GETTING SHOWN
Sheet sheet = workbook.createSheet("All Applications List");
Row header = sheet.createRow(0);
header.createCell(0).setCellValue("ID");
header.createCell(1).setCellValue("DESC");
header.createCell(2).setCellValue("DESC");
header.createCell(3).setCellValue("LINK_NOTES"); //THIS COLUMN NOT GETTING DISPLAYED
int rowNum = 1;
for (LinkAppl la : linkAppls) {
Row row = sheet.createRow(rowNum++);
row.createCell(0).setCellValue(la.getApplId());
row.createCell(1).setCellValue(la.getApplDeTx());
row.createCell(2).setCellValue(la.getApplActvCd());
row.createCell(3).setCellValue(la.getLinkNotesTx());
}
}
}
LinkAppl.java
#Entity
#Table(name = "LINK_APPL")
public class LinkAppl {
private String applId;
private String applDeTx;
private String seqNbResetCd;
private String intfMsgFrmtCd;
private String sndRcvCd;
private String applAcptMsgFrmtCd;
private String applActvCd;
private String sodEodIn;
private String linkNotesTx;
private String lastModByUsrId;
private Timestamp lastModTs;
private String sndCnctStsCd;
private Long maxSeqNb;
private String batIntfIn;
private String gfpSrcSiteCd;
private String rcvRterAckmentIn;
private String rcvMqCodIn;
private String fxApplIn;
private String rcvEodpAckmentIn;
//getters and setters go here
}
applications.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>Link Statistics Report</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h4>Excel Generation Demo</h4>
<table border="1">
<thead>
<tr>
<td>App ID</td>
<td>Name</td>
<td>Active</td>
</tr>
</thead>
<tbody>
<tr th:each="a : ${linkAppls}">
<td th:text="${a.applId}">App ID</td>
<td th:text="${a.getApplDeTx()}">Description</td>
<td th:text="${a.applActvCd}">Active</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="7">
Export to Excel
</td>
</tr>
</tfoot>
</table>
</body>
</html>
pom.xml
<!-- for handling .xls files (older format) -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.0.1</version>
</dependency>
<!-- for handling .xlsx files (newer format) -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.0.1</version>
</dependency>
The two ModelAndViews in your controllers are exactly the same.
return new ModelAndView("applications", "linkAppls", linkApplService.getAllLinkAppls());
is exactly the same in the download controller:
return new ModelAndView("applications", "linkAppls", linkApplService.getAllLinkAppls());
Setting the content-disposition doesn't change anything in the way spring is handling your request, and if you opened up applications.xls in a text editor, you would discover that you've just downloaded the html of your page renamed to be an .xls file. You need to figure out how to correctly wire up and use the AbstractXlsView that you've created.
Downloading a file:
#GetMapping("/download")
public void download(HttpServletResponse response) throws Exception {
Iterable<LinkAppl> linkAppls = linkApplService.getAllLinkAppls();
Workbook workbook = new HSSFWorkbook();
Sheet sheet = workbook.createSheet("All Applications List");
Row header = sheet.createRow(0);
header.createCell(0).setCellValue("ID");
header.createCell(1).setCellValue("DESC");
header.createCell(2).setCellValue("DESC");
header.createCell(3).setCellValue("LINK_NOTES");
int rowNum = 1;
for (LinkAppl la : linkAppls) {
Row row = sheet.createRow(rowNum++);
row.createCell(0).setCellValue(la.getApplId());
row.createCell(1).setCellValue(la.getApplDeTx());
row.createCell(2).setCellValue(la.getApplActvCd());
row.createCell(3).setCellValue(la.getLinkNotesTx());
}
response.setHeader("Content-disposition", "attachment; filename=" + EXCEL_FILE_NAME);
workbook.write(response.getOutputStream());
}
So finally with immense help from #Metroids I was able to download an excel file via controller. I also experimented with downloading an existing file located in src/main/resources folder. Here is the source code for better understanding.
applications.html
Export to Excel
Export to Excel 2
ExcelReportController.java
#Controller
#Log4j2
public class ExcelReportController {
private static final String EXCEL_FILE_NAME = "applications.xls";
#Autowired
private LinkApplService linkApplService;
#GetMapping("/excel")
public ModelAndView showPage() {
return new ModelAndView("applications", "linkAppls", linkApplService.getAllLinkAppls());
}
#GetMapping(value = "/download")
public void download(HttpServletResponse response) {
response.addHeader("Content-Disposition", "attachment; filename=" + EXCEL_FILE_NAME);
try {
//download an existing file located in src/main/resources folder
File file = ResourceUtils.getFile("classpath:" + EXCEL_FILE_NAME);
InputStream inputStream = new FileInputStream(file);
IOUtils.copy(inputStream, response.getOutputStream());
response.flushBuffer();
inputStream.close();
} catch (IOException e) {
log.error("Error while locating file", e);
}
}
#GetMapping(value = "/buildNDownload")
public void buildNDownload(HttpServletResponse response) throws IOException {
response.setHeader("Content-disposition", "attachment; filename=applications_new.xlsx");
Iterable<LinkAppl> linkAppls = linkApplService.getAllLinkAppls();
//build a file from scratch and then download
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("All Applications List");
Row header = sheet.createRow(0);
header.createCell(0).setCellValue("ID");
header.createCell(1).setCellValue("DESC");
header.createCell(2).setCellValue("ACTIVE");
header.createCell(3).setCellValue("LINK_NOTES");
int rowNum = 1;
for (LinkAppl la : linkAppls) {
Row row = sheet.createRow(rowNum++);
row.createCell(0).setCellValue(la.getApplId());
row.createCell(1).setCellValue(la.getApplDeTx());
row.createCell(2).setCellValue(la.getApplActvCd());
row.createCell(3).setCellValue(la.getLinkNotesTx());
}
workbook.write(response.getOutputStream());
}
}
pom.xml
<!-- for handling .xls files (older format) -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.0.1</version>
</dependency>
<!-- for handling .xlsx files (newer format) -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>

Liferay autofields: retrieving indexes in the controller

I´m trying to use auto-fields in the configuration of my portlet, but I´m getting desperate with an issue: in the action, I can retrieve the datafields but not the fields indexes in the controller. When I get it from the action request, it´s an empty String :(
Here´s the code from the jsp corresponding to the fields:
<div id="fyhespecials">
<div class="lfr-form-row lfr-form-row-inline">
<div class="row-fields">
<aui:input id='fecha0' name="fecha0" label="Fecha" />
<aui:input id='horario0' name="horario0" label="Horario" />
</div>
</div>
</div>
Here´s the script:
<aui:script use="liferay-auto-fields">
AUI().ready('liferay-auto-fields', function(A) {
new Liferay.AutoFields(
{
contentBox: '#fyhespecials',
fieldIndexes: '<portlet:namespace/>indexes'
}
).render();
});
</aui:script>
And in the controller, I just can´t get the indexes from the actionRequest, but I can get the fields "fecha(index)" and "horario(index)". However, I need the indexes to get the fields properly, so I´m stuck right now. Maybe is saved within the actionRequest, but named in a different way.
Would appreciate some help :)
Thanks in advance,
Luis.
PS: just for providing additional info (in case it was useful), the portlet is running in a Liferay 6.0
EDIT: As requested, here is the code in the controller that tries to catch de String of indexes. Note that, in the syso made below, this String comes empty, while the fields (fecha0, fecha1...) are shown correctly:
public class ListadoMuseoConfigurationActionImpl extends
DefaultConfigurationAction {
public void processAction(PortletConfig portletConfig,
ActionRequest actionRequest, ActionResponse actionResponse)
throws Exception {
String portletResource = ParamUtil.getString(actionRequest,
"portletResource");
PortletPreferences preferences = PortletPreferencesFactoryUtil
.getPortletSetup(actionRequest, portletResource);
//...
String indicesString= actionRequest.getParameter("indexes");
String fechaEspecial = ParamUtil.getString(actionRequest, "fecha0");
String fechaEspecial1 = ParamUtil.getString(actionRequest, "fecha1");
//...
System.out.println("=============Indices autofields======="+indicesString);
System.out.println("=============fechaEspecial======="+fechaEspecial);
System.out.println("=============fechaEspecial1======="+fechaEspecial1);
Hope this helps to get to a solution.

RichFaces 4 fileupload clear and clear all buttons

Well currently I have this:
<rich:fileUpload addLabel="Agregar" clearAllLabel="Quitar todos"
clearLabel="Quitar" deleteLabel="Quitar"
doneLabel="Completado" uploadLabel="Subir archivos"
fileUploadListener="#{uploadBean.doUpload}"
acceptedTypes="txt, csv"
noDuplicate="true">
<a4j:ajax event="uploadcomplete" render="validationButton"/>
<a4j:ajax event="clear" listener="#{uploadBean.doClearFilesList}"
render="validationButton"/>
</rich:fileUpload>
On the backing bean I have a list of the files uploaded. When I click on Clear/Clear all button the event clear is fired and the method doClearFilesList (which just clears the list of files uploaded) is perfectly when the user hits the Clear All button, but If the user clicks on Clear button It should just delete the item on the list corresponding to the file cleared.
What can I do on my UploadBean.doClearFilesList method to delete a single file from the list? Should be something like:
public void doClearFilesList(){
files.clear(); //when CLEAR ALL is clicked
files.remove(oneFile); //when CLEAR is clicked
validationButtonRendered = false;
}
Any idea?
Cheers
UPDATE
RichFaces 4.1.0 Final
JSF Mojarra 2.1.6
Tomcat 7
I am not clear at which point you failed to run the sample described at https://community.jboss.org/message/727544#727544
However I hope following would work for you which is very similar to above sample.
Page:
<h:head>
<script>
function clear(event) {
var files = new Array();
var data = event.rf.data;
for (var i in data) {
files[i] = data[i].name;
}
clearFunc(files);
}
</script>
</h:head>
<body>
<h:form>
<rich:fileUpload onclear="clear(event);"/>
<a4j:jsFunction name="clearFunc" action="#{del.clearFile}" ajaxSingle="true">
<a4j:param name="fName" assignTo="#{del.fileNames}" />
</a4j:jsFunction>
</h:form>
</body>
Class:
public class Del {
String[] fileNames;
public void clearFile() {
for(String name : fileNames) {
System.out.println(">>" + name);
//Do file removing part here
}
}
public String[] getFileNames() {
return fileNames;
}
public void setFileNames(String[] fileNames) {
this.fileNames = fileNames;
}
}
Add "onclear" attribute to your <rich:fileUpload/> component and call a <a4j:jsFunction/> and pass the file name to it as below.
<rich:fileUpload onclear="clearFunc(event.memo.entry.fileName);" ..../>
Your <a4j:jsFunction/> should be as below.
<a4j:jsFunction name="clearFunc" actionListener="#{uploadBean.clearFile}" ajaxSingle="true">
<a4j:actionparam name="fName" />
</a4j:jsFunction>
Inside the listener method you can access the file name as below.
public void clearFile(ActionEvent event) {
FacesContext context = FacesContext.getCurrentInstance();
String fileName = context.getExternalContext().getRequestParameterMap().get("fName").toString();
System.out.println("fileName = " + fileName);}

JaxB EclipseLink/MOXy : Supposedly empty date marshalled as today's date instead of no writing a node for it

Once again I have a question about Eclipselink/MOXy with external metadata mapping file.
I have a reference xml which applies to a class. This xml contains data that applies to some but not always all the properties that the class can contain.
I also have a custom datetime adapter set for the date fields.
My problem is that the xml I'm unmarshalling does not contain any data for the endDate property, yet when I do this simple test :
Unmarshall reference xml to the class
Marshall that class to a new xml file
Compare the two xml files
That property endDate (which should not be marshalled since it has not been set) is marshalled as 09/01/2012 17:05:28 (it's always marshalled as a new Date() set to the current time).
Here is a sample XML Metadata file :
<?xml version="1.0"?>
<xml-bindings xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm"
version="2.1">
<java-types>
<java-type name="sample.clazz.Task" xml-accessor-type="NONE">
<xml-root-element name="Task" />
<xml-type prop-order="startDate endDate id ci ch cr" />
<java-attributes>
<xml-element java-attribute="startDate" xml-path="StartDate/text()">
<xml-java-type-adapter value="utils.JaxBDateTimeAdapter" type="java.util.Date"/>
</xml-element>
<xml-element java-attribute="endDate" required="false" xml-path="EndDate/text()">
<xml-java-type-adapter value="utils.JaxBDateTimeAdapter" type="java.util.Date"/>
</xml-element>
<xml-element java-attribute="id" xml-path="TaskId/text()" />
<xml-element java-attribute="ci" xml-path="CIPR/text()" />
<xml-element java-attribute="ch" xml-path="CHPR/text()" />
<xml-element java-attribute="cr" xml-path="CRPR/text()" />
</java-attributes>
</java-type>
</java-types>
</xml-bindings>
Here is the class :
package sample.clazz;
public class Task{
private int id;
private Date startDate;
private Date endDate;
private String ci;
private String ch;
private String cr;
public Task(){
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
public String getCi() {
return ci;
}
public void setCi(String ci) {
this.ci = ci;
}
public String getCh() {
return ch;
}
public void setCh(String ch) {
this.ch = ch;
}
public String getCr() {
return cr;
}
public void setCr(String cr) {
this.cr = cr;
}
}
Here is my custom DateTimeAdapter :
package utils;
import java.util.Date;
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class JaxBDateTimeAdapter extends XmlAdapter<String, Date> {
#Override
public String marshal(Date d) throws Exception {
if(d != null){
return DateUtil.getFormatedDateTimeString(d);
}
else{
return null;
}
}
#Override
public Date unmarshal(String d) throws Exception {
if(d != null && !"".equals(d)){
return DateUtil.getDateFromString(d);
}
else{
return null;
}
}
}
Here is my reference XML
<?xml version="1.0" encoding="UTF-8"?>
<Task>
<TaskId>147</TaskId>
<CRPR>0087</CRPR>
<CIPR>A683557</CIPR>
<CHPR>BV</CHPR>
<StartDate>22/01/2009 20:56:29</StartDate>
</Task>
and Here is the XML I'm getting when re-marshalling the object :
<?xml version="1.0" encoding="UTF-8"?>
<Task>
<TaskId>147</TaskId>
<CRPR>0087</CRPR>
<CIPR>A683557</CIPR>
<CHPR>BV</CHPR>
<StartDate>01/01/2012 20:56:29</StartDate>
<EndDate>09/01/2012 17:05:28</EndDate> <!-- That element should not exist ! -->
</Task>
It seems like Jaxb generates a new date for the empty field, how can I tell him via the external metadata mapping file not to generate nodes for empty or null values ? I tried to set required=false on the metadata file, and I tried testing with my custom DateTimeAdapter if the values were null, but it seems Jaxb creates a new Date object and passes it to the marshal method of the Adapter. I cant think of any way of preventing him to do this.
As for my previous questions, I have no control over the incoming XML's or the model classes.
Please note : this data is a sample I wrote, it may not be accurate since I cannot expose real data or names, there might be some typing errors.
Thanks for your help.
I'm the EclipseLink JAXB (MOXy) lead and I have not been able to reproduce your issue. It may be possible that there is a problem in your DateUtil class. The following is what I have tried:
oxm.xml
I made a small change to your metadatafile. Basically I changed it to specify the package name on the xml-bindings element rather than the individual java-type elements:
<?xml version="1.0"?>
<xml-bindings
xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm"
version="2.3"
package-name="sample.clazz">
<java-types>
<java-type name="Task" xml-accessor-type="NONE">
<xml-root-element name="Task" />
<xml-type prop-order="startDate endDate id ci ch cr" />
<java-attributes>
<xml-element java-attribute="startDate" xml-path="StartDate/text()">
<xml-java-type-adapter value="forum8791782.JaxBDateTimeAdapter" type="java.util.Date"/>
</xml-element>
<xml-element java-attribute="endDate" required="false" xml-path="EndDate/text()">
<xml-java-type-adapter value="forum8791782.JaxBDateTimeAdapter" type="java.util.Date"/>
</xml-element>
<xml-element java-attribute="id" xml-path="TaskId/text()" />
<xml-element java-attribute="ci" xml-path="CIPR/text()" />
<xml-element java-attribute="ch" xml-path="CHPR/text()" />
<xml-element java-attribute="cr" xml-path="CRPR/text()" />
</java-attributes>
</java-type>
</java-types>
</xml-bindings>
DateUtil
You did not provide an implementation of DateUtil in your question, so I used the following. My guess is there is code in your implementation of DateUtil that is causing the output that you are seeing:
package forum8791782;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateUtil {
private static SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
public static String getFormatedDateTimeString(Date d) {
return formatter.format(d);
}
public static Date getDateFromString(String d) {
try {
return formatter.parse(d);
} catch(Exception e) {
throw new RuntimeException(e);
}
}
}
Demo
Below is the code I used to run this example. input.xml is the reference XML you cite in your question:
package forum8791782;
import java.io.File;
import java.util.*;
import javax.xml.bind.*;
import org.eclipse.persistence.Version;
import org.eclipse.persistence.jaxb.JAXBContextFactory;
import sample.clazz.Task;
public class Demo {
public static void main(String[] args) throws Exception {
System.out.println(Version.getVersionString());
Map<String, Object> properties = new HashMap<String, Object>(1);
properties.put(JAXBContextFactory.ECLIPSELINK_OXM_XML_KEY, "forum8791782/oxm.xml");
JAXBContext jc = JAXBContext.newInstance(new Class[] {Task.class}, properties);
File xml = new File("src/forum8791782/input.xml");
Unmarshaller u = jc.createUnmarshaller();
Task task = (Task) u.unmarshal(xml);
Marshaller m = jc.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
m.marshal(task, System.out);
}
}
Output
The following is the output I get from running the sample code. I do not see the EndDate element written out.
2.3.2.v20111125-r10461
<?xml version="1.0" encoding="UTF-8"?>
<Task>
<StartDate>22/01/2009 20:56:29</StartDate>
<TaskId>147</TaskId>
<CIPR>A683557</CIPR>
<CHPR>BV</CHPR>
<CRPR>0087</CRPR>
</Task>

Resources