XML becomes more and more important in java applications and is widely used in data storage and exchange. for example, common configuration files are stored in XML format. XML is also applied to technologies such as JavaMessageService and WebServices for data exchange. therefore, correct reading and writing of XML documents is the basis of XML applications. 1. xml parsing
XML becomes more and more important in java applications and is widely used in data storage and exchange. for example, common configuration files are stored in XML format. XML is also used in Java Message Service, Web Services and other technologies as data exchange. therefore, correct reading and writing of XML documents is the basis of XML applications.
Java provides two methods for parsing XML: SAX and DOM, but even so, it is not easy to read and write a slightly complex XML.
II. Introduction to XMLBean
Hibernate has become a popular object/relational database ing tool for Java environments. before the emergence of object/relational database ing tools such as Hibernate, database operations were implemented through JDBC. for any database operations, developers should write their own SQL statements. after the object/relational database ing tool appears, database operations are converted to operations on JavaBean, which greatly facilitates database development. therefore, if there is a similar tool that can convert XML read/write into a JavaBean operation, it will simplify XML read/write, developers who are not familiar with XML can easily read and write XML. this tool is XMLBean.
3. prepare XMLBean and XML documents
XMLBean is an open source project of Apache and can be downloaded from the http://www.apache.org. The latest version is 2.0. the directory after decompression is as follows:
xmlbean2.0.0 +---bin +---docs +---lib +---samples +---schemas
In addition, you must prepare an XML document (customers. xml ),
In this example, we will read and write this document. the source code of this document is as follows:
1
female
Jessica
Lim
1234567
350106
#25-1 SHINSAYAMA 2-CHOME
Ms Danielle
350107
#167 NORTH TOWER HARBOUR CITY
2
male
David
Bill
808182
319087
1033 WS St. Tima Road
Mr William
672993
1033 WS St. Tima Road
This is a data model of a customer. each customer has a customer ID, name, gender, phoneNumber, and address. the addresses include: primaryAddress and Bill address. each address consists of a zip code, address 1, and address 2. the bill address also contains the recipient ). in addition, a configuration file (File name: customer. xsdconfig). I will talk about the role of this file later. its content is as follows:
sample.xmlbean
IV. procedure for using XMLBean
Similar to other Java-Oriented Object/relational database ing tools, we need to make two preparations before using XMLBean.
1. generate an XML Schema file
What is an XML Schema file? Under normal circumstances, each XML file has a Schema file, which is an XML constraint file that defines the structure and elements of the XML file. and constraints on elements and structures. in general, if an XML file is a record in a database, Schema is the table structure definition.
Why is this file required? XMLBean needs to use this file to understand the structure and constraints of an XML file, such as the data type. using this Schema file, XMLBean will generate a series of related Java Classes for XML operations. as a developer, Java Classes generated by XMLBean are used to perform XML operations without the need for SAX or DOM. how to generate this Schema file? If you are familiar with XML, you can write this Schema file by yourself. for developers who are not familiar with XML, you can use some tools. for example, XMLSPY and Stylus Studio can generate Schema files through XML files. the Schema file (customer. xsd ):
2. use scomp to generate Java Classes
Scomp is a compilation tool provided by XMLBean. it is in the bin directory. through this tool, we can generate the above Schema file Java Classes. scomp syntax as follows :-
scomp [options] [dirs]* [schemaFile.xsd]* [service.wsdl]* [config.xsdconfig]*
Description of main parameters:
-Src [dir] -- generated Java Classes storage directory-srconly -- do not compile Java Classes, do not generate Jar file-out [jarFileName] -- generated Jar file, xmltypes by default. jar-compiler -- Java compiler path, that is, the Javac location schemaFile. xsd -- XML Schema file location
Config. xsdconfig -- the location of the xsdconfig file. This file is mainly used to develop some file naming rules for the generated Java Class and the name of the Package. in this article, the package is sample. xmlbean.
In this article, I run:
scomp -src build\src -out build\customerXmlBean.jar schema\customer.xsd -compiler C:\jdk142_04\bin\javac customer.xsdconfig
This command line tells scomp to generate customerXmlBean. jar, which is placed in the build directory, and the generated source code is put under build \ src. the Schema file is customer. the xsdconfig file is customer. xsdconfig. in fact, the generated Java source code does not have much effect. what we need is the jar file. let's take a look at the Classes generated under build \ src \ sample \ xmlbean.
CustomersDocument. java -- mertype is mapped to the Java Class of the entire XML document. java -- AddressType of node sustomer. java -- Biling of node address BillingAddressType. java -- ing of node billingAddress PrimaryAddressType. java -- ing of node primaryAddress
Now all our preparations have been completed. next we will focus on reading and writing XML using the generated jar file.
5. use XMLBean to read XML files
Create a Java Project and add the Jar file in XMLBean2.0.0 \ lib \ and the customerXmlBean. jar file we just generated to the ClassPath of the Project.
Create a Java Class: mermerxmlbean. the source code is as follows:
package com.sample.reader; import java.io.File; import sample.xmlbean.*; import org.apache.commons.beanutils.BeanUtils; import org.apache.xmlbeans.XmlOptions; public class CustomerXMLBean { private String filename = null; public CustomerXMLBean(String filename) { super(); this.filename = filename; } public void customerReader() { try { File xmlFile = new File(filename); CustomersDocument doc = CustomersDocument.Factory.parse(xmlFile); CustomerType[] customers = doc.getCustomers().getCustomerArray(); for (int i = 0; i < customers.length; i++) { CustomerType customer = customers[i]; println("Customer#" + i); println("Customer ID:" + customer.getId()); println("First name:" + customer.getFirstname()); println("Last name:" + customer.getLastname()); println("Gender:" + customer.getGender()); println("PhoneNumber:" + customer.getPhoneNumber()); // Primary address PrimaryAddressType primaryAddress = customer.getAddress().getPrimaryAddress(); println("PrimaryAddress:"); println("PostalCode:" + primaryAddress.getPostalCode()); println("AddressLine1:" + primaryAddress.getAddressLine1()); println("AddressLine2:" + primaryAddress.getAddressLine2()); // Billing address BillingAddressType billingAddress = customer.getAddress().getBillingAddress(); println("BillingAddress:"); println("Receiver:" + billingAddress.getReceiver()); println("PostalCode:" + billingAddress.getPostalCode()); println("AddressLine1:" + billingAddress.getAddressLine1()); println("AddressLine2:" + billingAddress.getAddressLine2()); } } catch (Exception ex) { ex.printStackTrace(); } } private void println(String str) { System.out.println(str); } public static void main(String[] args) { String filename = "F://JavaTest//Eclipse//XMLBean//xml//customers.xml"; CustomerXMLBean customerXMLBean = new CustomerXMLBean(filename); customerXMLBean.customerReader(); } }
Run it. see the output result:
Customer#0 Customer ID:1 First name:Jessica Last name:Lim Gender:female PhoneNumber:1234567 PrimaryAddress: PostalCode:350106 AddressLine1:#25-1 AddressLine2:SHINSAYAMA 2-CHOME BillingAddress: Receiver:Ms Danielle PostalCode:350107 AddressLine1:#167 AddressLine2:NORTH TOWER HARBOUR CITY Customer#1 Customer ID:2 First name:David Last name:Bill Gender:male PhoneNumber:808182 PrimaryAddress: PostalCode:319087 AddressLine1:1033 WS St. AddressLine2:Tima Road BillingAddress: Receiver:Mr William PostalCode:672993 AddressLine1:1033 WS St. AddressLine2:Tima Road
How is it easy? The power of XMLBean.
6. use XMLBean to write XML files
Creating an XML document using XMLBean is also a breeze. let's add another Method,
Java Class:
public void createCustomer() { try { // Create Document CustomersDocument doc = CustomersDocument.Factory.newInstance(); // Add new customer CustomerType customer = doc.addNewCustomers().addNewCustomer(); // set customer info customer.setId(3); customer.setFirstname("Jessica"); customer.setLastname("Lim"); customer.setGender("female"); customer.setPhoneNumber("1234567"); // Add new address AddressType address = customer.addNewAddress(); // Add new PrimaryAddress PrimaryAddressType primaryAddress = address.addNewPrimaryAddress(); primaryAddress.setPostalCode("350106"); primaryAddress.setAddressLine1("#25-1"); primaryAddress.setAddressLine2("SHINSAYAMA 2-CHOME"); // Add new BillingAddress BillingAddressType billingAddress = address.addNewBillingAddress(); billingAddress.setReceiver("Ms Danielle"); billingAddress.setPostalCode("350107"); billingAddress.setAddressLine1("#167"); billingAddress.setAddressLine2("NORTH TOWER HARBOUR CITY"); File xmlFile = new File(filename); doc.save(xmlFile); } catch (Exception ex) { ex.printStackTrace(); } }
Modify main method.
public static void main(String[] args) { String filename = "F://JavaTest//Eclipse//XMLBean//xml//customers_new.xml"; CustomerXMLBean customerXMLBean = new CustomerXMLBean(filename); customerXMLBean.createCustomer(); }
Run and open customers_new.xml:
3
female
Jessica
Lim
1234567
350106
#25-1 SHINSAYAMA 2-CHOME
Ms Danielle
350107
#167 NORTH TOWER HARBOUR CITY
7. use XMLBean to modify XML files
Let's add another Method:
public void updateCustomer(int id,String lastname) { try { File xmlFile = new File(filename); CustomersDocument doc = CustomersDocument.Factory.parse(xmlFile); CustomerType[] customers = doc.getCustomers().getCustomerArray(); for (int i = 0; i < customers.length; i++) { CustomerType customer = customers[i]; if(customer.getId()==id){ customer.setLastname(lastname); break; } } doc.save(xmlFile); } catch (Exception ex) { ex.printStackTrace(); } } main method: public static void main(String[] args) { String filename = "F://JavaTest//Eclipse//XMLBean//xml//customers_new.xml"; CustomerXMLBean customerXMLBean = new CustomerXMLBean(filename); customerXMLBean.updateCustomer(3,"last"); }
After running, we will see that the lastname of the customer with the customer number 3 has been changed to last.
8. use XMLBean to delete a customer
Add another Method:
public void deleteCustomer(int id) { try { File xmlFile = new File(filename); CustomersDocument doc = CustomersDocument.Factory.parse(xmlFile); CustomerType[] customers = doc.getCustomers().getCustomerArray(); for (int i = 0; i < customers.length; i++) { CustomerType customer = customers[i]; if(customer.getId()==id){ customer.setNil() ; break; } } doc.save(xmlFile); } catch (Exception ex) { ex.printStackTrace(); } } main method: public static void main(String[] args) { String filename = "F://JavaTest//Eclipse//XMLBean//xml//customers_new.xml"; CustomerXMLBean customerXMLBean = new CustomerXMLBean(filename); customerXMLBean.deleteCustomer(3); }
Run, we will see that the customer information with the customer number 3 has been deleted.
9. Query XML
In addition to the above description, XMLBean can easily complete XML read/write operations. combined with XPath and XQuery, XMLBean can also conveniently Query XML data like an SQL query database. I will discuss XML queries and how to create an XML database in another article.
10. Conclusion
XMLBean can help us read and write XML easily, which will help us to learn and use XML. With this foundation, developers will learn more XML-related technologies and Web Services, other J2EE technologies such as JMS lay a good foundation.
The above is the use of XMLBean to easily read and write XML content. For more information, please follow the PHP Chinese network (www.php1.cn )!