I found nothing online about how to read/write an XML document in JSF. I know something in JSP along with JSTL using XALAN. For example,
The following XML file is defined under /WEB-INF
.
<?xml version="1.0" encoding="UTF-8"?>
<fruits>
<fruit>
<name>Orange</name>
<price>10</price>
</fruit>
<fruit>
<name>Banana</name>
<price>20</price>
</fruit>
<fruit>
<name>Apple</name>
<price>30</price>
</fruit>
</fruits>
This document can be read in JSP like the following.
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>
<c:import var="items" url="/WEB-INF/TextXML.xml"/>
<x:parse var="fruits" doc="${items}"/>
<table rules="all" border="1">
<tr>
<th>index</th>
<th>Fruit Name</th>
<th>Price</th>
</tr>
<x:forEach var="item" select="$fruits/fruits/fruit" varStatus="loop">
<tr>
<td><c:out value="${loop.index+1}"/></td>
<td><x:out select="$item/name" /></td>
<td><x:out select="$item/price" /></td>
</tr>
</x:forEach>
</table>
This would populate an HTML table with three columns.
How can the same thing be achieved in JSF, maybe by using JAXB or something else?
You can indeed use JAXB for this.
Let's assume that you already have a javabean representing
<fruit>
. You can even reuse an existing JPA entity for this.(note that javabean class and property names must exactly match XML element names
<fruit>
,<name>
and<price>
, otherwise you need a@XmlElement(name="actualXmlElementName")
on either of those)Now, create another javabean representing
<fruits>
, purely for usage in JAXB (it namely requires a@XmlRootElement
class representing the XML root element, even though the XML document basically only contains a list of entities).As to reading/writing, you can in JSF perfectly read from
/WEB-INF
as follows:But writing is a story apart. You aren't supposed to write files to deployment space. It isn't intented as permanent storage location for the obvious reason that all changes will get lost whenever you redeploy the WAR. You need to write it to a fixed path somewhere outside the deploy space. In the below example I'll assume that the file is moved to
/var/webapp/fruits.xml
on the server's disk file system.So, you can use JAXB to read and write the XML file in a managed bean as follows:
You can display it for editing in a JSF
<h:dataTable>
the usual way.