< Day Day Up > |
XML Beans is a WebLogic Workshop tool that provides a simple, intuitive means of accessing and editing XML documents. XML Beans evolves the state of XML parsing beyond that of JAXB by
As a result, XML Beans offers both more flexibility in representing XML data and, in most cases, comparableif not fasterprocessing of data than previously developed XML parser APIs.
Setting Up XML Beans in WebLogic WorkshopTo use XML Beans in your Workshop application, you must first select the XML document types to be handledvia their Schemaand then generate the affiliated Java data handling classes. This configuration is handled visually, without any code-level development. Creating a Schema ProjectIf your application doesn't already contain a Schema project, you must add one at this time. As described in Chapter 2, "Getting to Know the WebLogic Workshop IDE," you add a project by following these steps:
The New Project dialog box with appropriate Schema project settings is shown in Figure 10.1. If the default application type you're developing already includes a Schema project, note that creating a new Schema project might not be necessary. Figure 10.1. The New Project dialog provides an easy way to add a Schema project to an existing application.
Creating XML Beans InterfacesTo create the Java-based XML Beans interfaces for a certain class of XML documents, you must then import the XML Schema on which the documents are based. This is accomplished by following these steps:
Listing 10.3. The CasinoLayout.xsd Schema File<?xml version="1.0" encoding="UTF-8"?> <xs:schema targetNamespace="http://openuri.org/bea/samples/workshop/chap10/casinoLayout" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:cl="http://openuri.org/bea/samples/workshop/chap10/casinoLayout" elementFormDefault="qualified" attributeFormDefault="unqualified"> <xs:element name="casino" type="cl:casinoType"/> <xs:complexType name="casinoType"> <xs:sequence> <xs:element name="table" type="cl:tableType" maxOccurs="unbounded"/> </xs:sequence> </xs:complexType> <xs:complexType name="tableType"> <xs:sequence> <xs:element name="game"> <xs:simpleType> <xs:restriction base="xs:NMTOKEN"> <xs:enumeration value="blackjack"/> <xs:enumeration value="poker"/> <xs:enumeration value="slots"/> <xs:enumeration value="roulette"/> </xs:restriction> </xs:simpleType> </xs:element> <xs:element name="minimumBet"> <xs:simpleType> <xs:restriction base="xs:decimal"> <xs:totalDigits value='6'/> <xs:fractionDigits value='2'/> <xs:minInclusive value='0.25'/> <xs:maxInclusive value='1000.00'/> </xs:restriction> </xs:simpleType> </xs:element> </xs:sequence> <xs:attribute name="number" type="xs:int" use="required"/> </xs:complexType> </xs:schema> If the Schema file is not well formed (that is, is not syntactically correct), the Build pane shows the location and specifics of each error in red. Clicking on any error line immediately opens the Schema file in the Source View pane and highlights the code (see Figure 10.2). Figure 10.2. Workshop supplies clear indications of errors in Schema files when they are added to the project.
If the Schema file is well formed, the Build pane shows that the build was successful. In addition, the XML Bean classes are added to the Libraries folder as a JAR file with the same name as the Schema project. The classes are grouped in a package with a name corresponding to the namespace of the XML Schema document. For this example, as shown in Figure 10.3, this namespace http://openuri.org/bea/samples/workshop/chap10/casinoLayout Figure 10.3. Compiled XMLBean classes are added to the Libraries folder.
produces this package org.openuri.bea.samples.workshop.chap10.casinoLayout All classes in the Libraries folder are automatically added to the application's classpath, so they are available for immediate use in your application. The generated classes are also added to the XML Bean Classes folder under the Schema project. By default, every time a Schema file is edited and saved, the corresponding XML Bean classes are recompiled. To toggle this option off, follow these steps:
To rebuild the Schema project when this option is turned off, right-click on the Schema project folder and choose the Build < Name of Project > option. What If I Don't Have a Schema for My XML Document?If you don't have a Schema for the type of XML documents you want to handle, have no fear. A number of third-party products can be used to generate XML Schema from DTD files. BEA WebLogic Platform 8.1 includes the option to install an evaluation copy of one such package, Altova's XML Spy Enterprise Edition. If you installed this tool, follow these steps to create a Schema file from an XML document:
Table 10.2. Suggested Settings for XML Spy's Generate DTD/Schema Dialog Box
Invoking XML BeansXML Beans are created and handled by adding Java code to the appropriate application component in the Source View pane. To begin, you must add an import statement for the package in which the XML Beans interfaces reside. Don't be concerned if you forget the exact package name; as mentioned in Chapter 2, Workshop provides import statement code completion. Individual XML Bean calls are then added as needed to the application component's code. In addition to the document-specific interfaces, each with get and set methods that are similar to JavaBeans, the API offers a number of general interfaces, classes, and exceptions, all contained in the com.bea.xml package. Many of these components correspond to the built-in element types in the Schema specification. (For example, the XmlInt interface is linked to the xs:int type.) Others, such as the XmlOptions class, are linked to the operation of the XML parser. Complete API documentation on the com.bea.xml package is supplied in the WebLogic Workshop Reference, Workshop API Javadoc Reference, XML Beans API Reference section of the Reference Guide. You can open the Reference Guide by selecting Help, Reference Guide from the Workshop menu. Workshop's code completion mechanism gives you a guide to the syntax of available method calls. Creating XML BeansTo represent a complete XML document, Workshop creates a document interface; its name corresponds to the name of the root element with the word "Document" added to the end. New instances of this document are then created through the widely used Factory pattern: calling the newInstance() method on a Factory subclass of this document classin this case, CasinoDocument . Although the no-argument version of this method serves in many cases, Workshop also provides a variation that takes an XmlOptions argument. The XmlOptions object enables developers to configure a set of XML parser features for loading, saving, compiling, and validating XML documents. Settings include selecting the appropriate character encoding and allowing or stripping off whitespace and comments in the produced XML document. From this point, you build up the document, element by element, according to the hierarchy defined in the Schema. To do this, you call the appropriate add< object type > methods to create elements and call the corresponding set< object type > methods to set values for these elements. The complete code for creating the casinoLayout XML document is provided in Listing 10.4, and the resulting XML document is shown in Listing 10.5. Listing 10.4. Code to Create a casinoLayout XML Documentimport java.math.BigDecimal; import org.openuri.bea.samples.workshop.chap10.casinoLayout.CasinoDocument; import org.openuri.bea.samples.workshop.chap10.casinoLayout.CasinoType; import org.openuri.bea.samples.workshop.chap10.casinoLayout.TableType; public CasinoDocument getSampleCasino() { CasinoDocument casinoDoc = CasinoDocument.Factory.newInstance(); CasinoType casinoType = casinoDoc.addNewCasino(); TableType tableType = null; TableType.Game.Enum[] tableArray = { TableType.Game.BLACKJACK, TableType.Game.POKER, TableType.Game.ROULETTE, TableType.Game.SLOTS} ; double[] betArray = {10.00, 50.00, 5.00, 0.25}; for (int i = 0; i < 4; i++) { tableType = casinoType.addNewTable(); tableType.setGame(tableArray[i]); tableType.setMinimumBet(new BigDecimal(betArray[i])); tableType.setNumber(i+1); } return casinoDoc; } Listing 10.5. The Resulting casinoLayout XML Document<casino xmlns="http://openuri.org/bea/samples/workshop/chap10/casinoLayout"> <table number="1"> <game>blackjack</game> <minimumBet>10</minimumBet> </table> <table number="2"> <game>poker</game> <minimumBet>50</minimumBet> </table> <table number="3"> <game>roulette</game> <minimumBet>5</minimumBet> </table> <table number="4"> <game>slots</game> <minimumBet>0.25</minimumBet> </table> <table number="5"> <game>slots</game> <minimumBet>0.50</minimumBet> </table> </casino> After the XML document is created, you can store it or transfer it, just like any other Java object. For example, you can write the XMLBean to a file or pass it as a parameter to another Java method. Retrieving and Modifying Data from XML BeansThe XML Beans API offers multiple ways to gain access to an existing XML document through the overloaded parse() method. There are versions of this method that can take any of the following arguments:
All methods have corresponding versions with a second XmlOptions argument; for the sake of space, they are not listed here. After the document is retrieved, the appropriate get< object type > methods can be used to read element values from the document, and the add< object type > and set< object type > methods can be used for edits. When an element can occur more than once, as defined by a maxOccurs attribute set to greater than one or unbounded in the Schema, you need a means for programmatic iteration. In this case, the Workshop compiler is intelligent enough to generate special array-based get/set methods in the compiled XML Beans interface. For this example, a CasinoLayout document can have multiple Table elements. Therefore, the XML Beans interface includes getTableArray() and setTableArray() methods. Listing 10.6 supplies the code to process an instance of the casinoLayout XML document from the file and print a summary to standard output. Listing 10.6. Code for Processing a casinoLayout XML Documentpublic void printCasino(String casinoString) { try { CasinoDocument casinoDoc = CasinoDocument.Factory. parse(casinoString); CasinoType casino = casinoDoc.getCasino(); TableType[] tableArray = casino.getTableArray(); TableType currTable; TableType.Game.Enum gameType; double minBet; int tableNum; for (int i=0; i < tableArray.length; i++) { currTable = tableArray[i]; tableNum = currTable.getNumber(); gameType = currTable.getGame(); minBet = currTable.getMinimumBet().doubleValue(); System.out.println( "Table #" + tableNum + " - " + gameType.toString() + " - " + "$" + minBet); } } catch (com.bea.xml.XmlException xmle) { System.out.println("Invalid casino document"); } } |
< Day Day Up > |