Date post: | 16-Dec-2015 |
Category: |
Documents |
Upload: | edwina-doyle |
View: | 223 times |
Download: | 1 times |
XML and Data ManagemenXML and Data Managementt
11
Storing XML in ORDBMSStoring XML in ORDBMS
Amine KaddaraAmine Kaddara
Supervisor: Dr HaddoutiSupervisor: Dr Haddouti
22XML and Data ManagemenXML and Data Managementt
OutlineOutline
MotivationMotivation
Benefits of using ORDBMS for storing XMLBenefits of using ORDBMS for storing XML
Storage techniques using XORator algorithmStorage techniques using XORator algorithm
JDOM API (JavaDOM)JDOM API (JavaDOM)
JDOM ExamplesJDOM Examples
JDO API(Java Data Objects)JDO API(Java Data Objects)
JDO ExamplesJDO Examples
33XML and Data ManagemenXML and Data Managementt
MotivationMotivation
First, most database vendors today offer universal database products that combine their relational DBMS and ORDBMS offerings into a single product.
Second, an ORDBMS has a more expressive type system than an RDBMS.
Third, an ORDBMS is better suited for storing and querying XML documents that may use a richer set of data types.
44XML and Data ManagemenXML and Data Managementt
Motivation: ApplicationsMotivation: Applications
Computer-Aided Design (CAD)Computer-Aided Design (CAD)Computer-Aided Manufacturing (CAM)Computer-Aided Manufacturing (CAM)Computer-Aided Software Engineering (CASE)Computer-Aided Software Engineering (CASE)Network Management SystemsNetwork Management SystemsOffice Information Systems (OIS) and Multimedia Office Information Systems (OIS) and Multimedia SystemsSystemsDigital PublishingDigital PublishingGeographic Information Systems (GIS)Geographic Information Systems (GIS)Interactive and Dynamic Web sitesInteractive and Dynamic Web sitesOther applications with complex and interrelated Other applications with complex and interrelated objects and procedural data. objects and procedural data.
55XML and Data ManagemenXML and Data Managementt
Motivation: RDBMS weaknessesMotivation: RDBMS weaknesses
Poor Representation of “Real World” EntitiesPoor Representation of “Real World” Entities Normalization leads to relations that do not correspond to entities Normalization leads to relations that do not correspond to entities
in “real world”.in “real world”.
Semantic OverloadingSemantic Overloading Relational model has only one construct for representing data and Relational model has only one construct for representing data and
data relationships: the relation. data relationships: the relation. Relational model is Relational model is semantically overloadedsemantically overloaded..
Difficulty Handling Recursive QueriesDifficulty Handling Recursive Queries
RDBMSs are poor at navigational access to data.RDBMSs are poor at navigational access to data.
Limited OperationsLimited Operations RDBMs only have a fixed set of operations which are difficult to RDBMs only have a fixed set of operations which are difficult to
extend.extend.
66XML and Data ManagemenXML and Data Managementt
Motivation: ORDBMS AdvantagesMotivation: ORDBMS Advantages
Add object storage facilities to relational Add object storage facilities to relational databasedatabase Greater flexibility than strict relationalGreater flexibility than strict relational Easier to introduce into organisation than full OOEasier to introduce into organisation than full OO Backwards compatible with strict relational Backwards compatible with strict relational
applications, SQL etcapplications, SQL etc
Relational paradigm retainedRelational paradigm retained Tables with rows of valuesTables with rows of values But attributes can contain objects, sets, arrays, tuples But attributes can contain objects, sets, arrays, tuples
etcetc
77XML and Data ManagemenXML and Data Managementt
Motivation: ORDBMS AdvantagesMotivation: ORDBMS Advantages
Code held within database, as functions, Code held within database, as functions, procedures or methodsprocedures or methods common functionality can be centralised rather common functionality can be centralised rather
than re-implemented by every application that than re-implemented by every application that uses the datauses the data
BLOBs(Binary Large Objects)BLOBs(Binary Large Objects) and and CLOBs(Character Large Objects)CLOBs(Character Large Objects) are used to are used to store large unstructured values within store large unstructured values within databasedatabase allows storage of complex data e.g. multimediaallows storage of complex data e.g. multimedia
88XML and Data ManagemenXML and Data Managementt
Motivation: ORDBMS AdvantagesMotivation: ORDBMS Advantages
ORDBMSORDBMS The ability to directly manipulate data The ability to directly manipulate data stored in a relational database using an stored in a relational database using an object programming language is called object programming language is called transparent persistence transparent persistence Object-relational mapping means less Object-relational mapping means less code to writecode to writeHigher performance over an embedded Higher performance over an embedded SQL or a call interface(JDBC,ODBC) SQL or a call interface(JDBC,ODBC)
99XML and Data ManagemenXML and Data Managementt
XML and ORDBMSXML and ORDBMS
1010XML and Data ManagemenXML and Data Managementt
XORator mappingXORator mapping
The XORator(XML to OR Translator) algorithm is a practical demonstration of the use of XML data types It takes advantage of using an ORDBMS over an RDBMS.XORator uses Document Type Definitions (DTDs) to map XML documents to tables in an ORDBMS. An important part of this mapping is the assignmentof a fragment of an XML document to a new XML data type, called XADT (XML Abstract Data Type).
1111XML and Data ManagemenXML and Data Managementt
XORator: DTD -> OR schemaXORator: DTD -> OR schema
Reducing the DTD complexityReducing the DTD complexity
Building DTD graphBuilding DTD graph
Mapping DTD to OR schemaMapping DTD to OR schema
Defining XADT(XML Abstract Data Types)Defining XADT(XML Abstract Data Types)
1212XML and Data ManagemenXML and Data Managementt
XORator: DTD -> OR schema XORator: DTD -> OR schema <!ELEMENT PLAY (INDUCT?, ACT+)><!ELEMENT INDUCT (TITLE, SUBTITLE*, SCENE+)><!ELEMENT ACT (SCENE+, TITLE, SUBTITLE*, SPEECH+, PROLOGUE?)><!ELEMENT SCENE (TITLE, SUBTITLE*, (SPEECH | SUBHEAD)+)><!ELEMENT SPEECH (SPEAKER, LINE)+><!ELEMENT PROLOGUE (#PCDATA)><!ELEMENT TITLE (#PCDATA)><!ELEMENT SUBTITLE (#PCDATA)><!ELEMENT SUBHEAD (#PCDATA)><!ELEMENT SPEAKER (#PCDATA)><!ELEMENT LINE (#PCDATA)>
1313XML and Data ManagemenXML and Data Managementt
XORator: DTD complexity XORator: DTD complexity
Simplify the DTD information to a form that makes the mapping process easier.Set of transformations to reduce the number of nested expressions and the number of element items:
Flattening (to convert a nested definition into a flat representation): (e1,e2)* -> e1, e2
Simplification (to reduce multiple unary operators into a single unary operator) : e1**->e1*
Grouping (to group subelements that have the same name): e0; e1*; e1*; e2 -> e0; e1*; e2
In addition, e+ is transformed to e*.
1414XML and Data ManagemenXML and Data Managementt
XORator: DTD -> OR schemaXORator: DTD -> OR schemaThe simplified version of the previous DTD
<!ELEMENT PLAY (INDUCT?, ACT*)> <!ELEMENT INDUCT (TITLE, SUBTITLE*, SCENE*) <!ELEMENT ACT (SCENE*, TITLE, SUBTITLE*, SPEECH*,
PROLOGUE?)> <!ELEMENT SCENE (TITLE, SUBTITLE*, SPEECH*, SUBHEAD*)> <!ELEMENT SPEECH (SPEAKER*, LINE*)> <!ELEMENT PROLOGUE (#PCDATA)> <!ELEMENT TITLE (#PCDATA)> <!ELEMENT SUBTITLE (#PCDATA)> <!ELEMENT SUBHEAD (#PCDATA)> <!ELEMENT SPEAKER (#PCDATA)> <!ELEMENT LINE (#PCDATA)>
1515XML and Data ManagemenXML and Data Managementt
XORator: DTD -> OR schemaXORator: DTD -> OR schema
we build a DTD graph to represent the structure of the DTD.
Nodes in the DTD graph are elements, attributes, and operators.
In the DTD graph, elements that contain characters are duplicated to eliminate the sharing.
1616XML and Data ManagemenXML and Data Managementt
XORator: DTD -> OR schemaXORator: DTD -> OR schema
Given an DTD graph, a relation is created for nodes that satisfy any of these following conditions:
1) nodes that have an in-degree of zero
2) recursive nodes with in-degree greater than one
3) one node among mutually recursive nodes with in-degree one.
4) All remaining nodes (nodes not mapped to a relation) are inlined as attributes under the relation created for their closest ancestor nodes (in the DTD graph).
1717XML and Data ManagemenXML and Data Managementt
1818XML and Data ManagemenXML and Data Managementt
XORator: DTD -> OR schemaXORator: DTD -> OR schema
An XADT attribute can store a fragment of an XML document
The XORator algorithm allows mapping an entire subtree of the DTD graph to an attribute of the XADT.
1919XML and Data ManagemenXML and Data Managementt
2020XML and Data ManagemenXML and Data Managementt
XORator: XADTXORator: XADT
A storage representation is to use a compressed representation for each XML fragment.The element tags are mapped to integer codes, and element tags are replaced by these integer codes. A small dictionary is stored along with the XML fragment to record the mapping between the integer codes and the actual element tag names.There is two implementations of the XADT: one that uses compression, and the other one that does not.
2121XML and Data ManagemenXML and Data Managementt
XORator: XADTXORator: XADT
The decision to use the “correct” implementation of the XADT is made during the document transformation process by monitoring the effectiveness of the compression technique.
Compression is used only if the space efficiency is above a certain threshold value.
2222XML and Data ManagemenXML and Data Managementt
XORator: XADTXORator: XADTXADT getElm(XADT inXML, VARCHAR rootElm, VARCHAR searchElm, VARCHAR searchKey, INTEGER level):
This Method returns all rootElm elements that have searchElm within a depth of level from the rootElm.
INTEGER findKeyInElm(XADT inXML, VARCHAR searchElm, VARCHAR searchKey):
This method examines all elements with the tag name searchElm in inXML, and searches for all searchElm elements with content that matches the searchKey keyword and returns 1 if true
XADT getElmIndex(XADT inXML, VARCHAR parentElm, VARCHAR childElm, INTEGER startPos, INTEGER endPos):
This method returns all childElm elements that are children of the parentElm elements and with the sibling order from startPos to endPos positions.
2323XML and Data ManagemenXML and Data Managementt
XORator: XADTXORator: XADT
This query retrieves lines that are spoken in acts by the ‘SPEAKER’ ‘HAMLET’ and have the keyword ‘friend’ in the line.
2424XML and Data ManagemenXML and Data Managementt
JDOMJDOM
JDOM is an open source, tree-based(DOM), pure Java API for parsing, creating, manipulating, and serializing XML documentsJDOM represents an XML document as a tree composed of elements, attributes, comments, processing instructions, text nodes, CDATA sections,etc..JDOM is written in and for Java. It consistently uses the Java coding conventions and the class library and it implemets the cloenable and serializable interfaces
2525XML and Data ManagemenXML and Data Managementt
JDOMJDOM
Xerces 1.4.4 is bundled with JDOM to parse XML documents.A JDOM tree is fully read-write. All parts of the tree can be moved, deleted, and added to, subject to the usual restrictions of XML. Unlike DOM, there are no annoying read-only sections of the tree that one can’t change.
2626XML and Data ManagemenXML and Data Managementt
JDOM ExampleJDOM Example
<person> <person> <name>Michael Owen</name> <name>Michael Owen</name> <address>222 Bazza Lane, Liverpool, <address>222 Bazza Lane, Liverpool,
MN</address> MN</address> <ssn>111-222-3333</ssn><ssn>111-222-3333</ssn><email>[email protected]</email> <email>[email protected]</email> <home-phone>720.111.2222</home-phone><home-phone>720.111.2222</home-phone><work-phone>111.222.3333</work-phone><work-phone>111.222.3333</work-phone></person></person>
2727XML and Data ManagemenXML and Data Managementt
JDOM ExampleJDOM Examplepublic class Person { public class Person { private String name; private String name; private String address; private String address; private String ssn; private String ssn; private String email; private String email; private String homePhone; private String homePhone; private String workPhone;// -- allows us to create a Personprivate String workPhone;// -- allows us to create a Personpublic Person(String name, String address, String ssn,public Person(String name, String address, String ssn,String email, String homePhone, String workPhone) { String email, String homePhone, String workPhone) { this.name = name; this.name = name; this.address = address; this.address = address; this.ssn = ssn; this.ssn = ssn; this.email = email; this.email = email; this.homePhone = homePhone; this.homePhone = homePhone; this.workPhone = workPhone; this.workPhone = workPhone; }// -- used by the data-binding}// -- used by the data-binding
2828XML and Data ManagemenXML and Data Managementt
JDOM ExampleJDOM Example
public Person() { }// -- accessors public Person() { }// -- accessors public String getName() { return name; } public String getName() { return name; } public String getAddress() { return address; } public String getAddress() { return address; } public String getSsn() { return ssn; } public String getSsn() { return ssn; } public String getEmail() { return email; } public String getEmail() { return email; } public String getHomePhone() { return homePhone; } public String getHomePhone() { return homePhone; } public String getWorkPhone() { return workPhone; }// -- mutators public String getWorkPhone() { return workPhone; }// -- mutators public void setName(String name) { this.name = name; } public void setName(String name) { this.name = name; } public void setAddress(String address) { this.address = address; }public void setAddress(String address) { this.address = address; }public void setSsn(String ssn) { this.ssn = ssn; } public void setSsn(String ssn) { this.ssn = ssn; } public void setEmail(String email) { this.email = email; } public void setEmail(String email) { this.email = email; } public void setHomePhone(String homePhone) { this.homePhone = public void setHomePhone(String homePhone) { this.homePhone =
homePhone; } homePhone; } public void setWorkPhone(String workPhone) { this.workPhone = public void setWorkPhone(String workPhone) { this.workPhone =
workPhone; }workPhone; }
2929XML and Data ManagemenXML and Data Managementt
JDOM ExampleJDOM Exampleimport org.exolab.castor.xml.*;import org.exolab.castor.xml.*;import java.io.FileReader;import java.io.FileReader;public class ReadPerson { public class ReadPerson { public static void main(String args[]) { public static void main(String args[]) { try { try { Person person = (Person) Unmarshaller.unmarshal(Person.class, new Person person = (Person) Unmarshaller.unmarshal(Person.class, new FileReader("person.xml")); FileReader("person.xml")); System.out.println("Person Attributes"); System.out.println("-----------------"); System.out.println("Person Attributes"); System.out.println("-----------------"); System.out.println("Name: " + person.getName() ); System.out.println("Name: " + person.getName() ); System.out.println("Address: " + person.getAddress() ); System.out.println("Address: " + person.getAddress() ); System.out.println("SSN: " + person.getSsn() ); System.out.println("SSN: " + person.getSsn() ); System.out.println("Email: " + person.getEmail() ); System.out.println("Email: " + person.getEmail() ); System.out.println("Home Phone: " + person.getHomePhone() ); System.out.println("Home Phone: " + person.getHomePhone() ); System.out.println("Work Phone: " + person.getWorkPhone() ); } System.out.println("Work Phone: " + person.getWorkPhone() ); } catch (Exception e) { catch (Exception e) { System.out.println( e ); System.out.println( e ); } } }}}}
3030XML and Data ManagemenXML and Data Managementt
JDOM ExampleJDOM Example
import org.exolab.castor.xml.*;import org.exolab.castor.xml.*;import java.io.FileWriter;import java.io.FileWriter;public class CreatePerson { public class CreatePerson { public static void main(String args[]) { public static void main(String args[]) { try {// -- create a person to work with try {// -- create a person to work with Person person = new Person("Bob Harris", "123 Foo Street", "222-222-Person person = new Person("Bob Harris", "123 Foo Street", "222-222-2222", "[email protected]", "(123) 123-1234", "(123) 123-1234");// -- 2222", "[email protected]", "(123) 123-1234", "(123) 123-1234");// -- marshal the person object out as a <person> marshal the person object out as a <person> FileWriter file = new FileWriter("bob_person.xml"); FileWriter file = new FileWriter("bob_person.xml"); Marshaller.marshal(person, file); Marshaller.marshal(person, file); file.close(); } file.close(); } catch (Exception e) { catch (Exception e) { System.out.println( e ); System.out.println( e ); } }} }}}
3131XML and Data ManagemenXML and Data Managementt
JDOM ExampleJDOM Exampleimport org.exolab.castor.xml.*;import java.io.FileWriter;import org.exolab.castor.xml.*;import java.io.FileWriter;import java.io.FileReader;import java.io.FileReader;public class ModifyPerson {public class ModifyPerson {public static void main(String args[]) { public static void main(String args[]) { try {try {
// -- read in the person// -- read in the personPerson person = (Person) Person person = (Person) Unmarshaller.unmarshal(Person.class, new FileReader("person.xml"));Unmarshaller.unmarshal(Person.class, new FileReader("person.xml"));
// -- change the name // -- change the name person.setName("David Beckham");person.setName("David Beckham");
// -- marshal the changed person back to disk // -- marshal the changed person back to disk FileWriter file = new FileWriter("person.xml");FileWriter file = new FileWriter("person.xml");Marshaller.marshal(person, file); Marshaller.marshal(person, file); file.close();file.close(); } catch (Exception e) {} catch (Exception e) {
System.out.println( e ); System.out.println( e ); } }} } }}
3232XML and Data ManagemenXML and Data Managementt
JDOJDO
Sun's Java Data Objects (JDO) standard. Sun's Java Data Objects (JDO) standard. JDO allows you to persist Java objects.JDO allows you to persist Java objects.It supports transactions and multiple users. It It supports transactions and multiple users. It differs from JDBC in that you don't have to think differs from JDBC in that you don't have to think about SQL and "all that database stuff." about SQL and "all that database stuff." It differs from serialization as it allows multiple It differs from serialization as it allows multiple users and transactions. users and transactions. It allows Java developers to use their object It allows Java developers to use their object model as a data model. There is no need to model as a data model. There is no need to spend time going between the "data" side and spend time going between the "data" side and the "object" side.the "object" side.
3333XML and Data ManagemenXML and Data Managementt
JDO: ExampleJDO: Examplepackage addressbook;package addressbook;import java.util.*;//OFimport java.util.*;//OFImport javax.jdo.*;Import javax.jdo.*;Importcom.prismt.j2ee.connector.jdbc.ManagedConnectionFactoryImpl;Importcom.prismt.j2ee.connector.jdbc.ManagedConnectionFactoryImpl;public class PersonPersist{ public class PersonPersist{ private final static int SIZE = 3; private final static int SIZE = 3; private PersistenceManagerFactory pmf = null; private PersistenceManagerFactory pmf = null; private PersistenceManager pm = null; private PersistenceManager pm = null; private Transaction transaction = null; private Transaction transaction = null; private Person[] people; private Person[] people; // Vector of current object identifiers // Vector of current object identifiers private Vector id = new Vector(SIZE); private Vector id = new Vector(SIZE); public PersonPersist() {public PersonPersist() { try { try { Properties props = new Properties(); Properties props = new Properties(); props.setProperty("javax.jdo.PersistenceManagerFactoryClass", props.setProperty("javax.jdo.PersistenceManagerFactoryClass", "com.prismt.j2ee.jdo.PersistenceManagerFactoryImpl"); "com.prismt.j2ee.jdo.PersistenceManagerFactoryImpl"); pmf = JDOHelper.getPersistenceManagerFactory(props); pmf = JDOHelper.getPersistenceManagerFactory(props); pmf.setConnectionFactory( createConnectionFactory() ); pmf.setConnectionFactory( createConnectionFactory() ); }} catch(Exception ex) { catch(Exception ex) { ex.printStackTrace();ex.printStackTrace(); System.exit(1); } } System.exit(1); } }
3434XML and Data ManagemenXML and Data Managementt
JDO: ExampleJDO: Example
public static Object createConnectionFactory() {public static Object createConnectionFactory() {ManagedConnectionFactoryImpl mcfi = new ManagedConnectionFactoryImpl mcfi = new ManagedConnectionFactoryImpl(); Object connectionFactory = null; ManagedConnectionFactoryImpl(); Object connectionFactory = null; try { try { mcfi.setUserName("scott"); mcfi.setUserName("scott"); mcfi.setPassword("tiger"); mcfi.setPassword("tiger"); mcfi.setConnectionURL("jdbc:oracle:thin:@localhost:1521:thedb"); mcfi.setConnectionURL("jdbc:oracle:thin:@localhost:1521:thedb"); mcfi.setDBDriver("oracle.jdbc.driver.OracleDriver");mcfi.setDBDriver("oracle.jdbc.driver.OracleDriver");connectionFactory = mcfi.createConnectionFactory(); connectionFactory = mcfi.createConnectionFactory(); } catch(Exception e) { } catch(Exception e) { e.printStackTrace();e.printStackTrace(); System.exit(1); } System.exit(1); } return connectionFactory;return connectionFactory;} }
3535XML and Data ManagemenXML and Data Managementt
JDO: ExampleJDO: Examplepublic void persistPeople() { // create an array of Person's public void persistPeople() { // create an array of Person's people = new Person[SIZE]; // create three people people = new Person[SIZE]; // create three people people[0] = new Person("Gary Segal", "123 Foobar Lane“,"123-123-1234", people[0] = new Person("Gary Segal", "123 Foobar Lane“,"123-123-1234",
"[email protected]", "(608) 294-0192", "(608) 029-4059"); "[email protected]", "(608) 294-0192", "(608) 029-4059"); people[1] = new Person("Michael Owen", "222 Bazza Lane, Liverpool, MN", people[1] = new Person("Michael Owen", "222 Bazza Lane, Liverpool, MN",
"111-222-3333", "[email protected]", "(720) 111-2222", "(303) 222- "111-222-3333", "[email protected]", "(720) 111-2222", "(303) 222-3333"); 3333");
people[2] = new Person("Roy Keane", "222 Trafford Ave, Manchester, MN", people[2] = new Person("Roy Keane", "222 Trafford Ave, Manchester, MN", "234-235-3830", "[email protected]", "(720) 940-9049", "(303) 309-7599)"); // "234-235-3830", "[email protected]", "(720) 940-9049", "(303) 309-7599)"); // persist the array of people persist the array of people
pm = pmf.getPersistenceManager(); pm = pmf.getPersistenceManager(); transaction = pm.currentTransaction(); transaction = pm.currentTransaction(); pm.makePersistentAll(people); pm.makePersistentAll(people); transaction.commit(); // retrieve the object ids for the persisted objects transaction.commit(); // retrieve the object ids for the persisted objects for(int i = 0; i < people.length; i++) { for(int i = 0; i < people.length; i++) { id.add(pm.getObjectId(people[i])); id.add(pm.getObjectId(people[i])); } // close current persistence manager to ensure that // objects are read from } // close current persistence manager to ensure that // objects are read from
the db not the persistence // manager's memory cache.the db not the persistence // manager's memory cache. pm.close();pm.close();}}
3636XML and Data ManagemenXML and Data Managementt
JDO: ExampleJDO: Example
public void change() { public void change() { Person person; // retrieve objects from datastore Person person; // retrieve objects from datastore pm =pmf.getPersistenceManager(); pm =pmf.getPersistenceManager(); transaction = pm.currentTransaction(); transaction = pm.currentTransaction(); // change DataString field of the second persisted object // change DataString field of the second persisted object person=(Person)pm.getObjectById(id.elementAt(1, false); person=(Person)pm.getObjectById(id.elementAt(1, false); person.setName("Steve Gerrard"); // commit the change person.setName("Steve Gerrard"); // commit the change
and close the persistence manager and close the persistence manager transaction.commit(); transaction.commit(); pm.close();pm.close();}}
3737XML and Data ManagemenXML and Data Managementt
JDOM ExampleJDOM Example <addressbook name="Manchester United Address Book"><addressbook name="Manchester United Address Book">
<person name="Roy Keane"> <person name="Roy Keane"> <address>23 Whistlestop Ave</address> <address>23 Whistlestop Ave</address> <ssn>111-222-3333</ssn> <ssn>111-222-3333</ssn> <email>[email protected]</email> <email>[email protected]</email> <home-phone>720.111.2222</home-phone> <home-phone>720.111.2222</home-phone> <work-phone>111.222.3333</work-phone> <work-phone>111.222.3333</work-phone> </person> </person> <person name="Juan Sebastian Veron"> <person name="Juan Sebastian Veron"> <address>123 Foobar Lane</address> <address>123 Foobar Lane</address> <ssn>222-333-444</ssn> <ssn>222-333-444</ssn> <email>[email protected]</email> <email>[email protected]</email> <home-phone>720.111.2222</home-phone> <home-phone>720.111.2222</home-phone> <work-phone>111.222.3333</work-phone> <work-phone>111.222.3333</work-phone> </person> </person></addressbook></addressbook>
3838XML and Data ManagemenXML and Data Managementt
JDOM: ExampleJDOM: Example
import java.util.List;import java.util.List;import java.util.ArrayList;import java.util.ArrayList;public class Addressbook { public class Addressbook { private String addressBookName; private String addressBookName; private List persons = new ArrayList(); private List persons = new ArrayList(); public Addressbook() { }// -- manipulate the List of Person public Addressbook() { }// -- manipulate the List of Person public void addPerson(Person person) { public void addPerson(Person person) { persons.add(person); }persons.add(person); }public List getPersons() { return persons; }public List getPersons() { return persons; }// -- manipulate the name of the address book // -- manipulate the name of the address book public String getName() { return addressBookName; }public String getName() { return addressBookName; }public void setName(String name) { this.addressBookName = public void setName(String name) { this.addressBookName =
name; }name; }}}
3939XML and Data ManagemenXML and Data Managementt
JDOM ExampleJDOM Example<?xml version="1.0"?><?xml version="1.0"?><mapping><mapping><description>A mapping file for our Address Book application</description><description>A mapping file for our Address Book application</description>
<class name="Person"><class name="Person"> <field name="name" type="string"> <field name="name" type="string"> <bind-xml name="name" node="attribute" /> <bind-xml name="name" node="attribute" /> </field> </field> <field name="address" type="string" /> <field name="address" type="string" /> <field name="ssn" type="string" /> <field name="ssn" type="string" /> <field name="email" type="string" /> <field name="email" type="string" /> <field name="homePhone" type="string" /> <field name="homePhone" type="string" /> <field name="workPhone" type="string" /> <field name="workPhone" type="string" /></class></class>
<class name="Addressbook"><class name="Addressbook"> <field name="name" type="string"> <field name="name" type="string"> <bind-xml name="name" node="attribute" /> <bind-xml name="name" node="attribute" /> </field> </field> <field name="persons" type="Person" collection="collection" /> <field name="persons" type="Person" collection="collection" /></class></class></mapping></mapping>
4040XML and Data ManagemenXML and Data Managementt
JDOM ExampleJDOM Exampleimport org.exolab.castor.xml.*;import org.exolab.castor.xml.*;import org.exolab.castor.mapping.*;import org.exolab.castor.mapping.*;import java.io.FileReader;import java.io.FileReader;import java.util.List;import java.util.List;import java.util.Iterator;import java.util.Iterator;public class ViewAddressbook { public class ViewAddressbook { public static void main(String args[]) { public static void main(String args[]) {
try { // -- Load a mapping file try { // -- Load a mapping file Mapping mapping = new Mapping(); Mapping mapping = new Mapping(); mapping.loadMapping("mapping.xml"); mapping.loadMapping("mapping.xml"); Unmarshaller un = new Unmarshaller(Addressbook.class); Unmarshaller un = new Unmarshaller(Addressbook.class); un.setMapping( mapping ); // -- Read in the Addressbook using the un.setMapping( mapping ); // -- Read in the Addressbook using the mapping mapping FileReader in = new FileReader("addressbook.xml"); FileReader in = new FileReader("addressbook.xml"); Addressbook book = (Addressbook) un.unmarshal(in); Addressbook book = (Addressbook) un.unmarshal(in); in.close(); in.close();
4141XML and Data ManagemenXML and Data Managementt
JDOM ExampleJDOM Example
// -- Display the addressbook // -- Display the addressbook System.out.println( book.getName() ); System.out.println( book.getName() ); List persons = book.getPersons(); List persons = book.getPersons(); Iterator iter = persons.iterator(); Iterator iter = persons.iterator(); while ( iter.hasNext() ) { while ( iter.hasNext() ) { Person person = (Person) iter.next(); Person person = (Person) iter.next(); System.out.println("\n" + person.getName() ); System.out.println("\n" + person.getName() ); System.out.println("-----------------------------");System.out.println("-----------------------------"); System.out.println("Address = "+ person.getAddress()); System.out.println("Address = "+ person.getAddress()); System.out.println("SSN = " + person.getSsn() ); System.out.println("SSN = " + person.getSsn() ); System.out.println("Home Phone = " + System.out.println("Home Phone = " + person.getHomePhone() ); } person.getHomePhone() ); }
} catch (Exception e) { } catch (Exception e) { System.out.println( e ); System.out.println( e ); } } }}
}}
4242XML and Data ManagemenXML and Data Managementt
The EndThe End