Parsing an XML Document into a Persistent Structure
The XML document file contains details of staff working within two departments. This exercise imports the document in its entirety.
JadeScript::persistentImport Method
The JadeScript class persistentImport method parses the XML document and creates an XML tree structure with persistent JADE objects, as shown in the following code fragment.
vars parser : JadeXMLDocumentParser; xmlDoc : WPXMLDocument; root : Root; begin root := Root.firstInstance; beginTransaction; create xmlDoc persistent; create parser transient;
We begin by creating a persistent instance of WPXMLDocument represented by the xmlDoc variable and a transient instance of JadeXMLDocumentParser represented by the parser variable, as shown in the following code fragment.
parser.setClassMapping(JadeXMLAttribute, WPXMLAttribute); parser.setClassMapping(JadeXMLCDATA, WPXMLCDATA); parser.setClassMapping(JadeXMLComment, WPXMLComment); parser.setClassMapping(JadeXMLText, WPXMLText); parser.setClassMapping(JadeXMLDocumentType, WPXMLDocumentType); parser.setClassMapping(JadeXMLElement, WPXMLElement); parser.setClassMapping(JadeXMLProcessingInstruction, WPXMLProcessingInstruction);
Class mapping is a necessary part of parsing XML documents into a structure composed of instances of persistent user subclasses. As a system class such as JadeXMLElement can have multiple user subclasses, JADE needs to know which subclass should be used to create persistent objects when an XML element is found in the document; for example, you may have two persistent user subclasses of JadeXMLElement, one to store information regarding cars and one related to car manufacturers. When parsing an XML document containing car information, the setClassMapping method is used to tell JADE to create instances of the car‑related subclass of JadeXMLElement, rather than that related to car manufacturers.
To parse XML documents into a persistent structure, JADE requires you to specify the mapping for all real JadeXMLNode system subclasses, regardless of whether there is an intent to use them all. This is done to prevent runtime exceptions if the file does in fact contain an XML node for which no mapping has been specified. Needless to say, parsing XML documents into a persistent structure requires you to have actually created user subclasses for all system subclasses first. The only exception is the JadeXMLDocument subclass, which is declared explicitly when the document is created prior to calling the parseDocumentFile method, as shown in the following code fragment.
parser.parseDocumentFile(xmlDoc, "c:\JadeXMLWhitePaper\Persistent XML Structure.xml"); xmlDoc.setName("All People"); root.allWPXMLDocuments.add(xmlDoc); commitTransaction; epilog delete parser; end;
When the mapping is complete, the file is parsed and the WPXMLDocument is populated with an XML tree structure. As the document is stored persistently, it is added to a collection for easy retrieval later.