XML

= XML = This portion of the paper will focus on XML (Extensible Markup Language). XML allows programmers to create their own structure. They can define their own tags and attributes that describe information in a meaningful way. For this paper I will describe what XML is, its advantage and disadvantages and also use it to demonstrate proficiency in this subject. To do so I will first make a program that will parse and display an XML file. After that I will create a second program that will build a document object and generate an XML file from it.

= Definition = = = = = = = = Purpose = XML is useful if you want to send structured data to other people without giving them your database info or any other method. It is a way to format data for delivery. It is easy to read and write XML documents in Java. In fact, it is generally easier to use XML than it is to use an "ad hoc" file format. Thus, using XML makes programs easier to write and more professional.

= Example = To start off, here is a quick example of XML encoding.



If you look at the above example, everything was created by the programmer. There is a product tag which lets the programmer knows that a product will be embedded in between the product tag. The programmer could’ve easily used item just as easily. It is up to what the programmer wants. The more specific and precise the name, the easier it will be to understand. This is the same for the description and price tag. Each created to provide even more specific information for the product. All tag has to end with  where //nameoftag// is whatever the original tag was.

XML documents can be created by using a text editor such as Notepad and can be typed. One great advantage of XML files are that they are easily readable by computer programs and by humans

= Rules = = =  XML has rules that govern how a programmer constructs an XML document. These rules allow application modules such as XML parsers to read them in a predictable way. This is similar to the way Microsoft Word understands how a Microsoft Word document is laid out. Without these rules, XML loses its power and flexibility.  All of these rules are spelled out in the XML specification maintained by the World Wide Web Consortium (W3C): http://www.w3c.org. The specification dictates the rules and syntax of how to create an XML document construction. An example of a rule is as follows:

All XML Elements Must Have a Closing Tag
In HTML, you will often see elements that don't have a closing tag:



In XML, it is illegal to omit the closing tag. All elements **must** have a closing tag:





1 - Programmer can look at the code and decipher what it is trying to do. 2 - XML is resilient to change. If a programmer wants to add a new element all he/she has to do is add it like so:



Now a program that processes the new data can still extract the old information in the same way—as the contents of the description and price elements. The program need not be updated, and it can tolerate different versions of the data format.

**Below is a tree view of the XML file:**



= Differences between XML and HTML =

XML and HTML are different and they both have different goals. They are designed for different purposes. Some people think that xml is an advanced version of html and it has come to replace html. It is not the case. Both will be there as they are used for different purposes.

- XML files are meant to hold data and data in an xml file is well described. If you look at an xml file you can say what it holds. For example if you find a number in an xml file you can find out easily what that number identifies, whether it is the number of products, or the price of a product etc. In html it is not the case.

- HTML is used to display the data in a formatted way. You can apply styles and use different layouts to display the data in an html file. The data that is displayed in an html file could come from an xml file.


 * Stick to this rule:** In simple words, html displays the data and xml holds the data!

= Steps on how to Design an XML Document: =

= Parsing XML Documents: =

An XML parser is needed to read and analyze contents of XML documents. 

A parser is a program that reads a document, checks whether it is syntactically correct, and takes some action as it processes the document.

A streaming parser reports the building blocks of an XML document. A tree-based parser builds a document tree.

= Parsers : = Two kinds of XML parsers are in common use.



- XP is an XML parser written in Java. The following are the advantages of XP: - XP is designed to be 100% conformant and correct - XP aims at High performance

Apart from the high level parser API, it also provides a low level API that supports the construction of different kinds of parser.

= When to use which = Streaming parsers are more efficient for handling large XML documents whose tree structure would require large amounts of memory. Tree-based parsers, however, are easier to use for most applications— the parse tree gives you a complete overview of the data, whereas a streaming parser gives you the information in bits and pieces.

= XML with JAVA = The most important benefit of XML is its simplicity. Though it is simple it is powerful enough to express complex data structures. Java is one of most important programming languages that is used for creating web pages. It is an object oriented language whose main purpose was to be used with embedded systems such as cell phones. But later it gained more importance to be used with Web pages that were dynamic in nature. Java Applet and servelets are the important mechanisms for implementing this. Another advantage of using Java is the concept of JavaBeans, which is a software component model for Java that allows the rapid development of an application by using a visual builder. DOM is one of the methods for accessing the structure of an XML document. An alternative is to use an event driven API.SAX is a simple API designed for XML. DocumentHandler is very important since it is called every time an element is found. A DocumentHandler is used as follows:



= JOX = JOX is a set of Java libraries that allows you to transfer data between XML documents and JavaBeans. JOX matches XML document to the fields of a bean and it will use a DTD when writing an XML document when one is available.JOX, unlike the other libraries, allows you to use any form of an XML document and any JavaBean without creating a separate schema to describe the mapping between Java and XML. Breeze XML Binder is the most complete Java/XML data binding solution available. Breeze creates JavaBeans directly created from the XML structures. A parser is a program that reads strings and decides whether the input conforms to the rules of a certain grammar. Some parsers—such as the DOM XML parser—build a parse tree in the process or report an error message when a parse tree cannot be constructed. Other parsers—such as the SAX XML parser—call user-specified methods whenever a part of the input was successfully parsed.

Below is an XML example using Java. I created a list of beer and placed it in the Beer.xml file and used Java to parse it and display it in a formatted output. The class BeerListParser can parse an XML document that contains a list of beer descriptions. Its parse methods takes the file name and returns an array of list of BeerName objects. Any website will be able to take the file and parse and display it in whatever manner the programmer chooses.
 * CODE: **

code format="java" import java.io.File; import java.io.IOException; import java.util.ArrayList; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.xml.sax.SAXException;

public class BeerListParser {  //Constructs a parser that can parse item lists. public BeerListParser throws ParserConfigurationException {     DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance; builder = dbfactory.newDocumentBuilder; XPathFactory xpfactory = XPathFactory.newInstance; path = xpfactory.newXPath; }

//Parses an XML file containing an item list. public ArrayList parse(String fileName) throws SAXException, IOException, XPathExpressionException {     File f = new File(fileName); Document doc = builder.parse(f);

ArrayList items = new ArrayList; int itemCount = Integer.parseInt(path.evaluate( "count(/items/item)", doc)); for (int i = 1; i <= itemCount; i++) {        String description = path.evaluate(               "/items/item[" + i + "]/product/description", doc); double price = Double.parseDouble(path.evaluate( "/items/item[" + i + "]/product/price", doc)); Beer pr = new Beer(description, price); int quantity = Integer.parseInt(path.evaluate( "/items/item[" + i + "]/quantity", doc)); BeerName it = new BeerName(pr, quantity); items.add(it); }     return items; }

private DocumentBuilder builder; private XPath path; } }

code



code format="java5" import java.util.ArrayList;

//This program parses an XML file containing an item list. //It prints out the items that are described in the XML file. public class BeerListParserFile {  public static void main(String[] args) throws Exception {     BeerListParser parser = new BeerListParser; ArrayList items = parser.parse("beers.xml"); System.out.println("Beer                             Price  QTY  TOTAL"); for (BeerName anItem : items) System.out.println(anItem.format); } }

code

code format="java" //Describes a quantity of an article to purchase. public class BeerName { //Constructs an item from the product and quantity.

public BeerName(Beer aProduct, int aQuantity) {     theProduct = aProduct; quantity = aQuantity; }

//Computes the total cost of this line item. //return the total price public double getTotalPrice {     return theProduct.getPrice * quantity; }

//Formats this item. //@return a formatted string of this item //  public String format {     return String.format("%-30s%8.2f%5d%8.2f",            theProduct.getDescription, theProduct.getPrice,            quantity, getTotalPrice); }

private int quantity; private Beer theProduct; } code

code format="java" //Describes a product with a description and a price. public class Beer {

//Constructs a product from a description and a price. public Beer(String aDescription, double aPrice) {     description = aDescription; price = aPrice; }

//Gets the Beer description. public String getDescription {     return description; }

//Gets the price. public double getPrice {     return price; }

private String description; private double price; } code

This is the XML file which contains the beers and their descriptions.

code format="xml"  Heiniken 2.95      6          Budweiser 1.95      12 code



Output Using a Different XML file code format="xml"  Heiniken 2.95      6          Budweiser 1.95      12          Coars 1.85      8          Icehouse 1.55      1          Corona 2.95      15       can code

The first example demonstrated how to read and XML file into an object and how to analyze and manipulate some of the content. In this example, the opposite will happen. I built up a Document object and then save it as an XML file. Instead of a formatted output the program will generate the XML file.

code format="java" import java.util.ArrayList; import org.w3c.dom.DOMImplementation; import org.w3c.dom.Document; import org.w3c.dom.ls.DOMImplementationLS; import org.w3c.dom.ls.LSSerializer;

//  This program demonstrates the item list builder. It prints the XML //  file corresponding to a DOM document containing a list of items. public class BeerXmlFile {  public static void main(String[] args) throws Exception {     ArrayList items = new ArrayList; items.add(new BeerName(new Beer("Heiniken", 2.95), 6)); items.add(new BeerName(new Beer("Budweiser", 1.95), 12));

BeerListBuilder builder = new BeerListBuilder; Document doc = builder.build(items); DOMImplementation impl = doc.getImplementation; DOMImplementationLS implLS = (DOMImplementationLS) impl.getFeature("LS", "3.0"); LSSerializer ser = implLS.createLSSerializer; String out = ser.writeToString(doc);

System.out.println(out); } } code



code format="java" import java.util.ArrayList; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Text;

// Builds a DOM document for an array list of items. public class BeerListBuilder { // Constructs an item list builder. public BeerListBuilder throws ParserConfigurationException {     DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance; builder = factory.newDocumentBuilder; }

// Builds a DOM document for an array list of items. public Document build(ArrayList items) {     doc = builder.newDocument; doc.appendChild(createItems(items)); return doc; }

// Builds a DOM element for an array list of items. private Element createItems(ArrayList items) {     Element e = doc.createElement("items");

for (BeerName anItem : items) e.appendChild(createItem(anItem));

return e;  }

// Builds a DOM element for an item. private Element createItem(BeerName anItem) {     Element e = doc.createElement("item");

e.appendChild(createProduct(anItem.getProduct)); e.appendChild(createTextElement( "quantity", "" + anItem.getQuantity));

return e;  }

// Builds a DOM element for a product. private Element createProduct(Beer p)  { Element e = doc.createElement("product");

e.appendChild(createTextElement( "description", p.getDescription)); e.appendChild(createTextElement( "price", "" + p.getPrice));

return e;  }

private Element createTextElement(String name, String text) {     Text t = doc.createTextNode(text); Element e = doc.createElement(name); e.appendChild(t); return e;  }

private DocumentBuilder builder; private Document doc; } code



code format="java" public class BeerName { // Constructs an item from the product and quantity. public BeerName(Beer aProduct, int aQuantity) {     theProduct = aProduct; quantity = aQuantity; }

// Computes the total cost of this line item. public double getTotalPrice {     return theProduct.getPrice * quantity; }

// Gets the product that this item describes. public Beer getProduct {     return theProduct; }

// Gets the quantity of the product that this item describes. public int getQuantity {     return quantity; }

// Formats this item. public String format {     return String.format("%-30s%8.2f%5d%8.2f",            theProduct.getDescription, theProduct.getPrice,            quantity, getTotalPrice); }

private int quantity; private Beer theProduct; } code



code format="java" public class Beer { // Constructs a product from a description and a price. public Beer(String aDescription, double aPrice) {     description = aDescription; price = aPrice; }

// Gets the product description. public String getDescription {     return description; }

// Gets the product price. public double getPrice {     return price; }

private String description; private double price; } code Below is what is outputted: an XML file with the product descriptions.



=UML Diagram of DOM interfaces = = = Below is a diagram (UML) denoting how the flow of logic works when using the DOM interface.



Introduction ** XML ** JavaBeans


 * Chapters **