Generate an XML document with JAXB via XML mode

xiaoxiao2021-03-06  40

The XML mode is an XML document structure based on XML representation. Many J2EE developers use XML mode instead of document type definition (DTD) to generate XML documents, because Different DTDs, XML mode supports multiple data types and namespaces.

People often need an XML document based on XML mode. For example, you might find yourself need an XML document based on an enterprise Javabeans deployment descriptor architecture (EJB-JAR_2_1.XSD).

The JAXB class generator included in the Oracle 10G XML Developer Kit (XDK) product version (download) is a compiler for generating Java classes from an XML schema. (You can build an XML mode using the Oracle JDeveloper 10g XML Mode Editor.) The JAXB class generator replaces the mode class generator in Oracle9i XDK, which generates the Java class representing various elements and complexType in XML mode. (Used for XML binding Java architecture, JAXB, is a technology for binding XML mode to Java code representation.) Then, J2EE developers can build Java classes generated by JAXB class builders. XML documentation in accordance with XML mode.

In the present technical description, we will generate Java classes from one sample XML mode using the JAXB class generator. Then we will create an example XML document from these Java classes.

Preparatory settings (Windows)

To generate a Java class from an XML schema using a JAXB class generator, Oracle 10G XDK Jaxb class generator class, and command-line utility ORAJAXB must join the classpath (ClassPath). Using the XDK_NT_10_1_0_2_0_production.zip file to the installation directory. Add /lib/xml.jar, /lib/xmlparserv2.jar and /lib/xmlmesg.jar to the classPath variable. is a directory installed in Oracle 10G XDK product version.

XML mode for generating Java classes

The JAXB class generator generates a Java class corresponding to the top-level element and top complexType elements. In XML mode, the element uses , ComplexType is represented by .

Below is an XML schema example, OracleCatalog.xsd, which consists of some top elements and top complexType elements:

Generate Java class

In this section, we will tell the process of generating Java classes from OracleCatalog.xsd. As mentioned earlier, the Java class is generated using the JAXB class generator command line interface Orajaxb:

> java oracle.xml.jaxb.orajaxb -schema oraclecatalog.xsd -outputdir classes

The following is some options for Orajaxb:

Outputdir

Specifies the directory where the Java class is generated. Schema Specifies the XML schema that generates Java classes from it. Targetpkg Specifies the name of the target package. In our example, the generated Java class is: Article.java, Article IMPL.Java, Oraclecatalog.java, OraclecatalogImpl.java, Catalog.Java, CatalogImpl.java, Journal.java, JournalFActory.java, and ObjectFactory.java. (Different from the XDK version used to generate these classes, the generated Java class may vary, but the implementation of these classes is the same.) Generate Java corresponding to each top element and top-level complexType in this sample XML mode Interface and Java class. The ObjectFactory.java class will also generate, which consists of some methods used to create interface objects, as shown below:

package jaxbderived.catalog; public class ObjectFactory {public jaxbderived.catalog.Journal createJournal () {jaxbderived.catalog.Journal elem = new jaxbderived.catalog.JournalImpl (ownerDocument); return elem;} public jaxbderived.catalog.Article createArticle () { jaxbderived.catalog.Article elem = new jaxbderived.catalog.ArticleImpl (ownerDocument); return elem;} public jaxbderived.catalog.Catalog createCatalog () {jaxbderived.catalog.Catalog elem = new jaxbderived.catalog.CatalogImpl (ownerDocument); return elem ;} public jaxbderived.catalog.OracleCatalog createOracleCatalog () {jaxbderived.catalog.OracleCatalog elem = new jaxbderived.catalog.OracleCatalogImpl (ownerDocument); return elem;} public Object newInstance (Class javaContentInterface) throws javax.xml.bind.JAXBException {Object Newinstance = null; string elemname = javacontentinterface.getName (); try {ife ("jaxbderived.catalog.raclectalog") {newinstance = new jaxbderived.catalog.Oraclecience gImpl (ownerDocument); return newInstance;}} catch (Exception e) {throw new javax.xml.bind.JAXBException (e.toString ());} return null;} public Object getProperty (String name) {return null;} public void setProperty (String name, Object value) {} public Object unmarshal (org.w3c.dom.Node node) throws javax.xml.bind.UnmarshalException {String elemName = node.getLocalName (); try {if (elemName.equals ( "OracleCatalog")) {jaxbderived.catalog.OracleCatalog unode = new jaxbderived.catalog.OracleCatalogImpl ((oracle.xml.parser.v2.XMLElement) node); return unode;}} catch (Exception e) {throw new javax. Xml.bind.unmarshalexception (e.tostring ());

} return null;} private oracle.xml.parser.v2.xmldocument OwnerDocument = new oracle.xml.parser.v2.xmldocument ();} OracleCatalog.java is generated using the JAXB class generator, corresponding to the top element in XML mode One of the Java classes, which is a Java interface generated in the top level element OracleCatalog in OracleCatalog.xsd mode.

Package jaxbderived.catalog; public interface oraclecatalog extens jaxbderived.catalog.catalog, javax.xml.bind.Element {}

OracleCatalog MiMPL.java is a Java class generated corresponding to OracleCatalog.xsd mode Top elements OracleCatalog:

package jaxbderived.catalog; public class OracleCatalogImpl extends jaxbderived.catalog.CatalogImpl implements jaxbderived.catalog.OracleCatalog {public OracleCatalogImpl (oracle.xml.parser.v2.XMLDocument ownerDoc) {super ( "OracleCatalog", "http: // jaxbderived / catalog ", ownerDoc);} public OracleCatalogImpl (String name, String namespace, oracle.xml.parser.v2.XMLDocument ownerDoc) {super (name, namespace, ownerDoc);} public OracleCatalogImpl (oracle.xml.parser.v2.XMLElement node ) {super (node);}}

Catalog.java is one of the Java classes generated by top-level ComplexType declarations in XML mode, which corresponds to the Java interface generated by OracleCatalog.xsd Mode Top ComplexType Catalog.

package jaxbderived.catalog; public interface Catalog {public void setTitle (java.lang.String t); public java.lang.String getTitle (); public void setPublisher (java.lang.String p); public java.lang.String getPublisher (); public java.util.list getjournal ();

CatalogImpl.java is a Java class generated corresponding to top-level complextype catalog:

package jaxbderived.catalog; public class CatalogImpl extends oracle.xml.jaxb.JaxbNode implements jaxbderived.catalog.Catalog {public CatalogImpl (oracle.xml.parser.v2.XMLDocument ownerDoc) {super ( "catalog", "http: // jaxbderived / catalog ", ownerDoc);} public CatalogImpl (String name, String namespace, oracle.xml.parser.v2.XMLDocument ownerDoc) {super (name, namespace, ownerDoc);} public CatalogImpl (oracle.xml.parser.v2. Xmlelement Node) {super (node);} public void settitle (java.lang.string t) {super.setjaxbattrstringValue ("Title", ", T);} public java.lang.string gettitle () {RETURN SUPER. getJaxbAttrStringValue ( "title", "");} public void setPublisher (java.lang.String p) {super.setJaxbAttrStringValue ( "publisher", "", p);} public java.lang.String getPublisher () {return super .GetjaxbattrstringValue ("Publisher", "");} public java.util.list getjournal () {Return (java.util.list) Super.getlist ("Journal", "http:// jaxbderived / catalog", this, 0);} Public Object CreateJaxbno DE (Oracle.xml.Parser.v2.xmlnode node) {string name = node.getlocalname (); string namespace = node.getnamespaceuri (); if (Namespace == null) Namespace = ""; if (Name.Equals) "journal") && namespace.equals ( "http: // jaxbderived / catalog")) {jaxbderived.catalog.JournalImpl obj = new jaxbderived.catalog.JournalImpl (getOwnerDocument ()); obj.populateNodeArray (node); return obj; } return null;} public void populatenodeaRray (Oracle.xml.Parser.v2.xmlnode node) {string name, name, name, oracle.xml.Parser.v2.xmlNode n = (Oracle.xml.Parser.v2.xmlnode) Node. Getfirstchild (); while (n! =

NULL) {name = n.GetLocalName (); Namespace = n.GetNamespaceuri (); if (Namespace == Null) Namespace = ""; if (Name.Equals ("Journal") && namespace.Equals ("http: / / jaxbderived / catalog ") {super.setnodevectorvalue (0, n);} n = (ORACLE.XML.PARSER.V2.XMLNODE) ​​N.GetnextSibling ();} super.populatenodeaRray (node);} static firm Object [ ] _Journal Final Object [] _catalog = {_journal}; protected object [] getSchemaObject () {return_catalog;}} Now let's continue to introduce the process of generating an XML document from these Java classes.

Create an XML document

In this section, we will create an XML document example from these Java classes generated using the JAXB class generator, OracleCatalog.xml.

Create CatalogIMPL from these Java classes and group CatalogIMPL class objects to build an XML document. First, import Javax.xml.bind packages.

Import javax.xml.bind. *;

These Oracle Jaxb classes are now imported now.

Import oracle.xml.jaxb. *;

Create a grouper to group the Catalog object into the XML document.

JAXBContextimpl jaxbcontext = new jaxbcontextimpl (); Marshaller Marshaller = jaxbcontext.createmarshaller ();

Now, create ObjectFactory, we will create a new instance of the implementation class. ObjectFactory is an important feature of JAXB because it provides code portability.

ObjectFactory Factory = New ObjectFactory ();

Create a Catalog element:

CatalogIMPL Catalog = (CatalogImpl) (Factory.createCatalog ());

Set the Title property of the Catalog element:

Catalog.Settitle ("Oracle Magazine");

Set the Publisher property of the Catalog element.

Catalog.SetPublisher ("Oracle Publishing");

Create a Journal element.

Factory.createJournal ();

Set the Date property of the Journal element.

Journal.Setdate ("November-December 2003");

Add a Journal element to a Catalog element.

Java.util.List journallist = catalog.getjournal (); Journallist.Add (journal);

Create an Article element in a Journal element.

Article IMPL ARTICLE = (Article.CreateArticle ()); sets the section property of the Article element.

Article.setsection ("XML");

Create a title element in the article element.

Article.Settitle ("Updating Xquery");

Add Article elements to the Journal element.

Java.util.list articles = journal.geticle (); articlelist.add (articles);

Create an Author element in the article element.

Java.util.list authorlist = article.getauthor (); authorlist.add ("jason hunter");

Similarly to the Journal element created using the steps described above, add another Journal element to create an example XML document OracleCatalog.xml. Then group the CatalogIMPL object to an XML document.

Marshaller.Marshal (Catalog, New FileoutputStream (XmLDocument);

This has generated oraclecatalog.xml:

Updating xquery </ title> <author> jason hunter </ author> </ article> </ journal> <journal date = "september-october 2003> < Article Section = "SQL"> <title> The Active Database </ Title> <Author> Cameron orourke </ Author> </ Article> </ journal> </ catalog></p> <p>The following is XMLConstructor.java, which is a program for creating an XML document from these Java classes:</p> <p>import jaxbderived.catalog *;. import oracle.xml.jaxb *;. import oracle.xml.parser.v2 *;. import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import javax .xml.bind *;. public class XMLConstructor {public void generateXMLDocument (File xmlDocument) {try {JaxbContextImpl jaxbContext = new JaxbContextImpl (); Marshaller marshaller = jaxbContext.createMarshaller (); ObjectFactory factory = new ObjectFactory (); CatalogImpl catalog = ( CatalogImpl) (factory.createCatalog ()); catalog.setTitle ( "Oracle Magazine"); catalog.setPublisher ( "Oracle Publishing"); JournalImpl journal = (JournalImpl) (factory.createJournal ()); journal.setDate ( "November -December 2003 "); Article MITITICLE = (Article.CreateArticle ()); Article.SetSection (" XML "); Article.SetTitle (" Updating XQuery "); java.util.list journallist = catalog.getjournal ( Journallist.Add (journal); java.util.list articles = journal.GetArticle (); articlelist.add (article); java.util.li ST AuthorList = Article.getauthor (); AuthorList.Add ("jason hunter"); further.createjournal ("September-October 2003"); Article = (Article)); Article = (Articles) Factory.createArticle ()); Article.SetSection ("SQL"); Article.Settitle ("The Active Database"); JournalList = Catalog.getjournal (); JournalList.Add (journal); Articles; Articles; Authorlist = Article.getauthor (); AuthorList.Add ("Cameron orourke"); Marshaller.Marshal (Catalog, New FileoutputStream (XMLDocument);</p> <p>} catch (ioException e) {system.out.println (e.tostring ());} catch (jaxbexception e) {system.out.println (e.tostring ());}} public static void main (String [] Argv) {string xmldocument = argv [0]; xmlconstructor xmlconstructor = new xmlconstructor (); xmlconstructor.generatexmldocument (new file (xmldocument));}} Congratulations! You have generated Java classes through JAXB, and then use these classes to build an XML document from the XML schema.</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-86261.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="86261" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.057</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = 'SAerOs0eNJZtEeQtMsMWL4nOfOQPKKmxqpj5qGzO_2F_2FBecY81SqIkTwlnIxWt4FKr4WJ_2BN4IrKrgb0LWt_2FAheNw_3D_3D'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>