View
213
Download
0
Category
Preview:
Citation preview
XML Programming
Thomas LeeE-Mail: thomas_c_lee@yahoo.com
XML Progamming - 2 © Thomas Lee, 2000-2001
Course Description
• This one-day workshop on XML programming will help you learn about the XML programming in B2B eCommerce and the implication of XML for web site development. XML (eXtensible Markup Language) defines a universal standard for electronically exchanging data for the B2B e-Commerce. It is supported by major IT vendors. Topics covered include: Background review of XML, Introduction to SAX, DOM and their usage. Simple Labs will be provided.
XML Progamming - 3 © Thomas Lee, 2000-2001
Course Outline
• XML Overview
• SAX
• DOM
• Lab 1
• Lab 2
• Lab 3
XML Progamming - 4 © Thomas Lee, 2000-2001
References• Books
– “Java and XML” Brett McLaughhlin, O’Reilly
• Online resources:
– http://www.xmlspy.com– http://www.w3.org/TR/xmsg/– http://www.w3.org/TR/xmlschema-1– http://www.w3org/TR/REC-xml-names– http://xml.apache.org
– http://www.alphaworks.ibm.com/tech/LotusXSL
– http://technet.oracle.com/tech/xml
XML Progamming - 5 © Thomas Lee, 2000-2001
Expected Background
. Basic Knowledge of HTML and XML.
• Basic Programming skill, such as visual• Basic, C++ or Java is a Plus !!!
XML Progamming - 6 © Thomas Lee, 2000-2001
Course Schedule
• 9:00 AM ~ 9:50 AM
Overview of XML and its usage in E-Commerce
• 10:00 AM~10:50 AM
Introduction to SAX Programming (Simple XML API)
• 11:00 AM ~ 11:50 AM Lab1
• 11:50 ~ 12:50 PM
Introduction to DOM Programming (Microsoft and Sun)
• 1:00 PM ~ 1:50 PM Lab2
• 2:00 PM ~ 2:50 PM
XML used in eCommerce Environment
• 3:00 PM ~ 4:00 PM Lab 3
XML Progamming - 7 © Thomas Lee, 2000-2001
Logistics
• Parking Permit
• Rest Room
• Café Tear
XML Progamming - 8 © Thomas Lee, 2000-2001
Course Instructor
• Thomas Lee
• Master in both Computer Science and Electronics
Engineer.
• Over 17 years industry experience.
• Has extensive experience in eCommerce
Application.
• Senior Consultant in Telecommunication Industry.
XML Progamming - 9 © Thomas Lee, 2000-2001
Attendee Introductions
• Your Name
• Background
• Why you take this course ?
• What you expect from this course ?
XML Progamming - 10 © Thomas Lee, 2000-2001
Quick Review of XML Background
• Background• In 1996, A new team of experts led by Jon
Bosak of Sun Microsystems and backed by W3 began to work on a new standard.
• Finalized in February in 1998 called XML.
• XML( eXtensible Markup Language) is derived from SGML ( Standard Generalized Markup Language).
• The percentage of IT shops in the US using XML in Web jumped from 1% to 16%.
XML Progamming - 11 © Thomas Lee, 2000-2001
Quick Review of XML Background
• Background• A typical enterprise will use 35-40 percent of its
programming budget in developing data extraction and updating programs for the sole purpose of information transfer between different databases and applications, XML is the best candidate for those purpose.
• The eXtensible Markup Language(XML) has been developed by the World Wide Web Consortium(W3C) XML Working Group to bring SGML (Standard Generalized Markup Language) to the Web.
XML Progamming - 12 © Thomas Lee, 2000-2001
Quick Review of XML Background
• Background• SGML is a language for the specification of
markup languages. SGML is parent of the well-known HyperText Markup Language(HTML).
• XML's design was conducted by looking at the strengths and weaknesses of SGML but without all the complex and rarely used features.
• The first working draft for XML was published in November 1996.
XML Progamming - 13 © Thomas Lee, 2000-2001
Quick Review of XML Background
• Why XML• Simple,
• open,
• self-describing,
• provides a basis for author identification and versioning at the element level.
• Machine-readable context information
• Separates content from presentation
• Supports multilingual documents
• Facilitates the comparison and aggregation of data
XML Progamming - 14 © Thomas Lee, 2000-2001
Quick Review of XML Background
• Why XML• Can embed multiple data types -- can contain
any possible data type
• form multimedia data (image, sound, video) to active components (Java applets)
• Can embed existing data
• ‘One server’ view for distributed data
• Wide-spread acceptance in the industry.
XML Progamming - 15 © Thomas Lee, 2000-2001
XML
DTD
HTML Resources XML
DataStore
Application
XSL
XPL
HTML/CSS
Display andReporting
XLL
XML DataTypes
Data Transfer
Definition and Structure
Link to otherresources
XML Schema
XML Technologies
XML Progamming - 16 © Thomas Lee, 2000-2001
Java and XML
• XML is an essential component in the Java 2 Platform, Enterprise Edition (J2EETM) and will be supported throughout the J2EE platform as a means for enabling business-to-business information interchange using XML.
• For robust, synchronous data messaging, Enterprise JavaBeansTM (EJBTM) architecture-based components (enterprise beans) can be used to create a business service object, and related XML content can be published on the web using JavaServer PagesTM technology. Currently, JavaServer Pages technology can be used to generate and consume XML between n-tier servers or between server and client.
XML Progamming - 17 © Thomas Lee, 2000-2001
Java and XML
• Java Messaging Service provides a means for asynchronous XML data messaging. In addition, EJB technology uses XML to describe its deployment properties, giving enterprise beans data portability in addition to their code portability.
XML Progamming - 18 © Thomas Lee, 2000-2001
Quick Review of XML Background
• XML Components– Header
» Instruction e.g. <?xml version='1.0' encoding='UTF-8' ?>
» Document Type Declaration
e.g <!DOCTYPE Course SYSTEM "Demo1.dtd">
– Content» Root Element, Data Element
e.g <Course>………</Course>
» Element Attributes
e.g <Course Semester=‘Spring’>
» References
e.g. <Price>&onedayPrice</Price>
» Unparsed Data
e.g.<![CDATA[ sdfdsff <>s<<<>> ]]>
XML Progamming - 19 © Thomas Lee, 2000-2001
Quick Review of XML Background
Well-Formed XML• Must start with an XML declaration
• Non-empty tags must match and nest properly
• Empty tags must end with />
• Must have exactly one root element
• Tag and attribute names are case-sensitive
• Attribute values must be quoted
XML Progamming - 20 © Thomas Lee, 2000-2001
Quick Review of XML Background
Rules for Well-Formed XML(1)– Mandatory Closing Tags The set of Tags is unlimited but all container tags
must have end tags. <tag>…</tag> <TAG>…</TAG>
• Example of legal XML– <Person>
<Name>Adam Smith</Name>
<Title>General Manager</Title>
<Age>42</Age></Person>
XML Progamming - 21 © Thomas Lee, 2000-2001
Quick Review of XML Background
Rules for Well-Formed XML(2)– Proper Element Nesting. All tags must be nested correctly. Like HTML, XML can
intermix tags and text, but tags may not overlap each other.
• Legal XML<Person>John Smith is an <role>advocate</role> for <technology>XML</technology></Person>
• Illegal XML<Person><Name>John </Name><KeyPoint><Hd>XML provides a data bus</Hd> </Person><More>…</More> </KeyPoint>
XML Progamming - 22 © Thomas Lee, 2000-2001
Quick Review of XML Background
Rules for Well-Formed XML(3)– Double-quote value delimiters
All attribute values must be enclosed in single or double quotation marks.
• Legal: <tag attribute = "value"> or <tag attribute = 'value'>
• Illegal: <font size = 6>
XML tags are case sensitive.
<myTAG><Mytag> are different
XML Progamming - 23 © Thomas Lee, 2000-2001
Quick Review of XML Background
Rules for Well-Formed XML(4)– Single tag elements. Singleton tags (called empty element or tags
without content) must be written in an abbreviated form using special XML syntax.
• Legal: <BR/>
<HR/>
• <TITLE></TITLE> is equivalent to <TITLE/>
• Illegal: <BR>
<HR>
XML Progamming - 24 © Thomas Lee, 2000-2001
Quick Review of XML Background
XML Document: Validation Two kinds of ways to define rules for the
document. These rules can be used to validate an XML document or used by XML authoring tools to guide the creation of an XML document.– Document Type Definition (DTD): This is
used to define a grammar for the tags and attributes. This syntax is supported, but deprecated by MicrosoftMicrosoft. It uses a special non-XML-based grammar
– XML Schema (XML-Data): This is a much richer and more extensible way to describe the rules for the content of a document and uses XML itself as a grammar.
XML Progamming - 25 © Thomas Lee, 2000-2001
Quick Review of XML Background
The attribute has a value that does not change throughout the document.
#FIXED
This value is specified in place of a keyword in the <!ATTLIST> tag. If a value is specified in the document, the default value is replaced. However, if the document leaves the attribute value blank, then the default value is assumed.
Default Value
The element must have a value for the attribute specified. If the value is not specified, the document will not be processed
#REQUIRED
The attribute may have a value declared, or it could be left empty.
#IMPLIED
ImplicationKeyword
XML Progamming - 26 © Thomas Lee, 2000-2001
Quick Review of XML Background
Sample of DTD ( Embedded)<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE Course [
<!ELEMENT Title (#PCDATA)>
<!ELEMENT Price (#PCDATA)>
<!ELEMENT Instructor (#PCDATA)>
<!ELEMENT Date (#PCDATA)>
<!ELEMENT Course (Title, Price, Instructor, Date) >
]>
<Course>
<Title>XML Programming</Title>
<Price>$275</Price>
<Instructor>AIT</Instructor>
<Date>March 17,2001</Date>
</Course>
XML Progamming - 27 © Thomas Lee, 2000-2001
Quick Review of XML Background
Sample of DTD (Reference)
Demo1.dtd
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE Course [
<!ELEMENT Title (#PCDATA)>
<!ELEMENT Price (#PCDATA)>
<!ELEMENT Instructor (#PCDATA)>
<!ELEMENT Date (#PCDATA)>
<!ELEMENT Course (Title, Price, Instructor, Date) >
]>
XML Progamming - 28 © Thomas Lee, 2000-2001
Quick Review of XML Background
Sample of DTD (Reference)
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE Course [<?SYSTEM “\DTD\Demo1.dtd”? >] >
<Course>
<Title>XML Programming</Title>
<Price>$275</Price>
<Instructor>AIT</Instructor>
<Date>March 17,2001</Date>
</Course>
XML Progamming - 29 © Thomas Lee, 2000-2001
Quick Review of XML Background
XML Schema • XML Schema is designed to replace and amplify
DTDs ( because DTD is a strange animal in XML
community)
• It offers an XML-centric means to constrain XML documents.
• Reference: http://www.w3.org/TR/xmlschema-1
XML Progamming - 30 © Thomas Lee, 2000-2001
Quick Review of XML Background
• Well-Formed XML: – A well-formed XML document does not
necessarily include a DTD or a schema.
• Valid XML: – XML that conforms to the vocabulary
specified in a DTD or schema.
XML Progamming - 31 © Thomas Lee, 2000-2001
Quick Review of XML Background
Namespaces• A mapping between an element prefix and a URI
• Is used for handling namespace collisions and defining data structures that allow parsers to handle collisions.
• Examples
<Airplane:Engine>
<Car:Seat>
• http://www.w3org/TR/REC-xml-names
XML Progamming - 32 © Thomas Lee, 2000-2001
Quick Review of XML Background
XSL and XSLT• XSL ( Extensible Stylesheet Language)
– Transforms and translates XML data from one XML format to another format.
• XSLT ( Extensible Stylesheet Language
Transformation)– A Complete Text-based transformation process.
• Reference:– Apache Xalan: http://xml.apache.org
– Lotus XSL Processor: http://www.alphaworks.ibm.com/tech/LotusXSL
– Oracle XSL Processor:http://technet.oracle.com/tech/xml
XML Progamming - 33 © Thomas Lee, 2000-2001
Quick Review of XML Background
XSL and XML Samplegreeting.xml<?xml version="1.0" standalone="yes"?><?xml-stylesheet href="greeting.xsl" type="text/xsl" ?>
<greeting>Hello World!</greeting>greeting.xsl<xsl:stylesheet xmlns:xsl="http://www.w3.org/TR/WD-xsl"> <xsl:template match="/"> <H1> <xsl:value-of /> </H1> </xsl:template></xsl:stylesheet>
XML Progamming - 34 © Thomas Lee, 2000-2001
Quick Review of XML Background
Xpath• The XPath Recommendation defines a path
language and expression syntax used by XSLT, XPointer, and XLink, it defines how a specific item within an XML document can be located.
• An XML document is considered a tree of nodes ( any piece of XML data, including elements, attributes, and textual data), where each node can be accessed by specifying the location in the tree at which it is located.
• Reference: http://www.w3.org/TR/xpath
XML Progamming - 35 © Thomas Lee, 2000-2001
Quick Review of XML Background
SAX• It is Simple API for XML
• It provides the means to parse a document.
• It provides an event-based framework for parser to parse XML data.
• Available parsers:– Sun’s Project x
– Oracle’s XML parser
– Apache’s Xerces
– IBM’s XML4J
• Reference:
http://www.w3.org/DOM
XML Progamming - 36 © Thomas Lee, 2000-2001
Quick Review of XML Background
DOM• It is an API for the Document Object Model
• It provides a means of manipulating the XML data.
• It provides a representation of an XML document as a tree.
• Reference:
http://www.w3.org/DOM
XML Progamming - 37 © Thomas Lee, 2000-2001
Quick Review of XML Background
SAX/DOMPros Cons
SAX Event-
driven,sequentialprocessing,
Fast Less memory
requirement can handle large
streams of XML thatmay come fromdatabase.
Web Application(Servlet)
Network-orientedprogramms
Does not retain stateknowledge
Programmer shouldhandle it.
Hard to visualize No way to re-navigate,
change it.
DOM Works on
top of SAX Build tree
structure
Can use XPath toperform the movementacross nodes.
Guidelines1. Loading XML as a
DOM object if less than50000 or so records
Requires huge memory
XML Progamming - 38 © Thomas Lee, 2000-2001
Quick Review of XML Background
XML Application:– Presentation ( XML + XSL)
– Communication (HTTP/XML, XML-PRC)
– Configuration» EJB ( deployment descriptor)
» Servlet API version 2.2.
XML Progamming - 39 © Thomas Lee, 2000-2001
Quick Review of XML Background
XML IDE & Editors
Examples:– Microsoft XML Notepad ( editor)– XML Spy 3.5(Editor & IDE)
» XML editing & validation» Schema/DTD editing & validation» XSL editing & transformation» Reference: http://www.xmlspy.com
XML Progamming - 40 © Thomas Lee, 2000-2001
SAX Programming
In Java
XML Progamming - 41 © Thomas Lee, 2000-2001
SAX Programming
• Guidelines– (1) Finding a Parser
» e.g. Apache Xerces parser
» http://xml.apache.org
– (2) Make sure which SAX Version: 1.0/2.0» We will use SAX 1.0 in our Lab
– (3) Make sure the following classes( packages) in your jar files ( we use utils.jar in our lab)
org.xml.sax, org.xml.sax.helper,
javax.xml.parser, com.sun.xml.parser
com.sun.xml.tree
XML Progamming - 42 © Thomas Lee, 2000-2001
SAX Programming
• Guidelines– (4)Prepare a XML document
– (5)Write Programs to parse XML document.
XML Progamming - 43 © Thomas Lee, 2000-2001
SAX Programming
• Run your first program– Run Script: SAXDemo1\Bulid.bat
– Java Program: SAXDemo1\SAXDemo1.java
– XML Document: SAXDemo1\ Demo0.xml
SAXDemo1\ Demo1.xml
SAXDemo1\ Demo2.xml
SAXDemo1\ Demo1.dtd
– Test Case 1: No DTD Validation
– Test Case 2: DTD Validation
XML Progamming - 44 © Thomas Lee, 2000-2001
SAX Programming
• SAX Related package
• org.xml.sax
• org.xml.sax.helpers
XML Progamming - 45 © Thomas Lee, 2000-2001
SAX Programming-SAXDemo1.javaImport necessary libraries• java.io.*
• org.xml.sax.*
• java.util.*;
• javax.xml.parsers.SAXParserFactory
• javax.xml.parsers.ParserConfigurationException
• javax.xml.parsers.SAXParser
Parser
API Interface
XML Progamming - 46 © Thomas Lee, 2000-2001
SAX Programming-SAXDemo1.java• org.xml.sax : -Defines the SAX interfaces
• org.xml.sax.helpers– It defines the ParserFactory class, which lets you acquire
an instance of a parser either by specifying a name string or by using the value defined by the org.xml.sax.parser system property.
• javax.xml.parsers– Defines the SAXParserFactory class which returns the
SAXParser
• com.sun.xml.parser– Contains the Java XML parser
(com.sun.xml.parser.Parser),
– validating parser (com.sun.xml.parser.ValidatingParser), and entity resolver
XML Progamming - 47 © Thomas Lee, 2000-2001
SAX Programming-SAXDemo1.javaContents in org.xml.sax package
Interfaces AttributeList Attributes ContentHandler DocumentHandler DTDHandler EntityResolver ErrorHandler Locator Parser XMLFilter XMLReader
Classes HandlerBase InputSource
Exceptions SAXException SAXNotRecognizedException SAXNotSupportedException SAXParseException
For SAX 1.0
Bold: for SAX 2.0
XML Progamming - 48 © Thomas Lee, 2000-2001
SAX Programming-SAXDemo1.javaContents in org.xml.sax.helpers package
Bold for SAX 2.0
Classes AttributeListImpl AttributesImpl DefaultHandler LocatorImpl NamespaceSupport ParserAdapter ParserFactory XMLFilterImpl XMLReaderAdapter XMLReaderFactory
XML Progamming - 49 © Thomas Lee, 2000-2001
SAX Programming-SAXDemo1.javaCreating /Setting Parser Object/Features
try{SAXParserFactory mfactory =
SAXParserFactory.newInstance();
mfactory.setValidating(bValidate); if (mfactory!=null){ SAXParser saxParser =
mfactory.newSAXParser();
saxParser.parse( new File(fileName), this); }} catch (SAXParseException spe) {…}catch(……){…}
Set DTDValidatingFeature
Create SAXParser
Read from FileUseful if we setvalidating to true
XML Progamming - 50 © Thomas Lee, 2000-2001
SAX Programming-SAXDemo1.java
Implements ContentHandler Functions(0)• SAX parser generates the following linear
events:– setDocumentLocator– start document– start element– characters– end element– end document
XML Progamming - 51 © Thomas Lee, 2000-2001
SAX Programming-SAXDemo1.javaImplementing ContentHandler Functions(1)
public void startElement (String name, AttributeList attrs)
throws SAXException
{
mFindName = name;
}
public void characters (char buf [], int offset, int len)
throws SAXException
{ String s = new String(buf, offset, len);
mTable.put(mFindName,s );
}
XML Progamming - 52 © Thomas Lee, 2000-2001
SAX Programming-SAXDemo1.javaImplementing ContentHandler Functions(2)public void endElement (String name)
throws SAXException
{ }
public void startDocument ()
throws SAXException
{ }
public void endDocument ()
throws SAXException
{ }
XML Progamming - 53 © Thomas Lee, 2000-2001
SAX Programming-SAXDemo1.javaImplementing ContentHandler Functions(3)public void setDocumentLocator (Locator l)
{
// Save this to resolve relative URIs or to give
// diagnostics.
System.out.println ("LOCATOR");
System.out.println ("\n SYS ID: " + l.getSystemId() );
}
output example:SYS ID: file:E:/XMLClass/SAXDemo1/Demo0.xml
XML Progamming - 54 © Thomas Lee, 2000-2001
SAX Programming-SAXDemo1.javaImplementing ErrorHandler Functions• Report the violation of a validity constraint. The default
behavior is to take no action
public void error (SAXParseException e)
throws SAXParseException
{ ………. }
• Default behaviour is to take no action.
public void warning (SAXParseException err)
throws SAXParseException
{ ….. }
XML Progamming - 55 © Thomas Lee, 2000-2001
SAX Programming-SAXDemo1.javaImplementing ErrorHandler Functions
Report the violation of a well-formedness constraint.
public void fatalError (SAXParseException ferr)
throws SAXParseException
{ throw ferr; }
XML Progamming - 56 © Thomas Lee, 2000-2001
SAX Programming-SAXDemo1.javaImplementing Test Procedurepublic static void main(String[] args) {
SAXDemo1 oDemo = new SAXDemo1();
Hashtable oTable;
try{
if( args[1].equals("v")||args[1].equals("V"))
oDemo.ProcessFromFile(args[0],true);
else
oDemo.ProcessFromFile(args[0],false);
oTable=oDemo.getResultTable();
System.out.println("Title: " + (String)oTable.get("Title"));
System.out.println("Price: " + (String)oTable.get("Price"));
System.out.println("Instructor: " +
(String)oTable.get("Instructor"));
System.out.println("Date: " + (String)oTable.get("Date"));
}catch(SAXParseException e){….} }
}
XML Progamming - 57 © Thomas Lee, 2000-2001
SAX Programming-SAXDemo1.javabulid.batset CLASSPATH=.;E:\XMLClass\xmlclasslib.jar;%CLASSPAH%
javac %1.java
java %1 %2 %3
Run the Script - case1 ( ignore validation)E:\XMLClass\SAXDemo1 >bulid SAXDemo1 Demo1.xml gLOCATOR
SYS ID: file:E:/XMLClass/SAXDemo1/Demo0.xml
Title: Introduction to XML Programming
Price: $275
Instructor: AIT
Date: null
XML Progamming - 58 © Thomas Lee, 2000-2001
SAX Programming-SAXDemo1.javaRun the Script - case2 (enforce validation)E:\XMLClass\SAXDemo1 >bulid SAXDemo1 Demo1.xml v
LOCATOR
SYS ID: file:E:/XMLClass/SAXDemo1/Demo0.xml
** Parsing error, line 7, uri file:E:/XMLClass/SAXDemo1/Demo0.xml
Element "Course" requires additional elements.
Sorry! this parsing cannot go through!
XML Progamming - 59 © Thomas Lee, 2000-2001
SAX Programming-SAXDemo1.java• SAX parser generates the following linear events:
– setDocument: SYS ID: file:E:/XMLClass/SAXDemo1/Demo0.xml– start document– start element: Course– start element: Title– characters: Introduction to XML Programming – end element : Title – start element: Price– characters: $275– end element : Price – ……………...– end element :Course– end document
XML Progamming - 60 © Thomas Lee, 2000-2001
SAX Programming-SAXDemo1.java• SAX parser generates the following linear events:
– setDocument: SYS ID: file:E:/XMLClass/SAXDemo1/Demo0.xml– start document– start element: Course– start element: Title– characters: Introduction to XML Programming – end element : Title – start element: Price– characters: $275– end element : Price – ……………...– end element :Course– end document
XML Progamming - 61 © Thomas Lee, 2000-2001
SAX Programming-SAXDemo1.java• Try to modify Demo1.dtd and SAXDemo1.java and rerun
bulid SAXDemo Demo1.xml v
and
bulid SAXDemo Demo1.xml g
XML Progamming - 62 © Thomas Lee, 2000-2001
DOM Programming
In Java
XML Progamming - 63 © Thomas Lee, 2000-2001
DOM Programming
• Demo files under XMLClass\DomDemo1• DomDemo2.java:Print out everything from a XML String
– Bulid DomDemo2
• DomDemo3.java: This sample show you how to parse a XML string and display name-value pair information
– Bulid DomDemo3
• DomDemo4.java: This sample show you how to parse a XML file and display Name-value pair information
– Bulid DomDemo4 Demo1.xml• DomDemo5.java:This sample show you how to parse a
XML file and provides collection of Element Name/value information
– Bulid DomDemo5 Demo1.xml
XML Progamming - 64 © Thomas Lee, 2000-2001
DOM Programming-DomDemo3.java
Processing Instruction Text Comment
EntityReference CDATASection Element
Document Type
comment
Processing Instruction Document
(Root) Element
Attributes
Attributes
EntitiesNotations
childNodes
DOM Model
XML Progamming - 65 © Thomas Lee, 2000-2001
DOM Programming-DomDemo3.java
Guidelines
– (1) Finding a Parser » e.g. Apache Xerces parser
» http://xml.apache.org
– (2) Make sure the following classes( packages) in your jar files ( we use utils.jar in our lab)
org.xml.sax, org.xml.sax.helper,
javax.xml.parser, com.sun.xml.parser
com.sun.xml.tree
XML Progamming - 66 © Thomas Lee, 2000-2001
DOM Programming-DomDemo3.java
Node:– Represents the basic class for all
document objects.
– Allow direct manipulation of the underlying document.
NodeList– Ordered in a manner consistent with a
preorder traversal of the parser treeRoot
Leftmost Right branch
XML Progamming - 67 © Thomas Lee, 2000-2001
DOM Programming-DomDemo3.java
NamedNodeMap– Collection of Node Objects.
– Used by Node object to return set of attributes.
– Access by Name.
CharacterData– Represents Text and Comment objects
XML Progamming - 68 © Thomas Lee, 2000-2001
DOM Programming-DomDemo3.java
Text– Characters between “StartTag” and
“Closing Tag” .
– Used by Node object to return set of attributes.
Element– Manages its attributes directly instead of as
children.
XML Progamming - 69 © Thomas Lee, 2000-2001
DOM Programming-DomDemo3.java
Attribute– Associated with the Elements that they are
declared with.
ProcessingInstruction
CDATASection– Unparsed text that is identified between
<![CDATA and ]]>
XML Progamming - 70 © Thomas Lee, 2000-2001
DOM Programming-DomDemo3.java
EntityReference– A holder for aliased parsed text.
XML Progamming - 71 © Thomas Lee, 2000-2001
DOM Programming-DomDemo3.java
• Import Librariesimport java.io.*;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Document;
import org.w3c.dom.DOMException;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.DocumentBuilder;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
XML Progamming - 72 © Thomas Lee, 2000-2001
DOM Programming-DomDemo3.java
Static Document document;try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder parser = factory.newDocumentBuilder(); factory.setValidating(true); factory.setNamespaceAware(true); document = parser.parse(new File(argv[0]));}catch(…){}
Create Parser
XML Progamming - 73 © Thomas Lee, 2000-2001
DOM Programming-DomDemo3.java
private String traversing(Node node) { String rValue=""; String name; NodeList child; switch(node.getNodeType()) { case Node.DOCUMENT_NODE: name= node.getNodeName(); child = node.getChildNodes(); if( child!=null)
{ for ( int i=0; i< child.getLength(); i++)
{ rValue= traversing(child.item(i));
if(!rValue.equals("")) return rValue; } } break;
Implement traversing
XML Progamming - 74 © Thomas Lee, 2000-2001
DOM Programming-DomDemo3.java
case Node.ELEMENT_NODE:name= node.getNodeName();
if( name.equals(sElName)) bFind=true; else bFind=false; child = node.getChildNodes(); if( child!=null)
{ for ( int i=0; i< child.getLength(); i++) { rValue = traversing(child.item(i)); if(!rValue.equals("")) return rValue; } }
break;
Implement traversing
XML Progamming - 75 © Thomas Lee, 2000-2001
DOM Programming-DomDemo3.java
case Node.TEXT_NODE: if(bFind) { rValue= node.getNodeValue(); return rValue; } break;case Node.CDATA_SECTION_NODE: //System.out.println(node.getNodeValue()); break; case Node.PROCESSING_INSTRUCTION_NODE: //System.out.println(node.getNodeValue()); break;case Node.ENTITY_REFERENCE_NODE: break;case Node.DOCUMENT_TYPE_NODE: break; } return "";}
Implement traversing
XML Progamming - 76 © Thomas Lee, 2000-2001
DOM Programming-DomDemo3.java
//Get Elment Value public String getElValue(String el) { sElName = el; return traversing(document); }
Provides a getElValue methodThis method provides the content inside a given Element name
XML Progamming - 77 © Thomas Lee, 2000-2001
DOM Programming-DomDemo3.java
DomDemo3 oDemo = new DomDemo3(); try { //create DOM Parser and parse the // given XML file or XML string and get back // XMLdocument objectSystem.out.println("Title:" + oDemo.getElValue("Title")); System.out.println("Instructor:" + ……. }
Catch(….){}
Use this getElValue
XML Progamming - 78 © Thomas Lee, 2000-2001
DOM Programming
In VB
XML Progamming - 79 © Thomas Lee, 2000-2001
DOM Programming in VB
• Make sure you have msxml.dll under your system/system32 directory
• Open VB Project
• Go to Project/References and select
Microsoft XML, version 2 library
• Use DOMDocument to process your XMLstring
XML Progamming - 80 © Thomas Lee, 2000-2001
DOM Programming in VB
• Methods Samples– loadXML
» Load XML input String into DomDocument Object
– Load» Load XML File into DomDocument Object.
– createAttribute, getElementsByTagName, abort, appendChild, cloneNode, createNode,save
• Member Samples– validateOnParse,……...
XML Progamming - 81 © Thomas Lee, 2000-2001
DOM Programming in VB
• Xml related data type– IXMLDOMNode
– IXMLDOMAttribute
– IXMLDOMElement
– IXMLDOMEntity
– IXMLDOMNamedNodeMap
– IXMLDOMText
– …………….
You can use the same approach in Java to do your DOM relatedwork in VB, Please see CXMLParser.cls filefor detail information
XML Progamming - 82 © Thomas Lee, 2000-2001
XML used in eCommerce Environment
HTTP/XML
XML Progamming - 83 © Thomas Lee, 2000-2001
XML used in eCommerce Environment
HTTP/XML
XML Progamming - 84 © Thomas Lee, 2000-2001
XML used in eCommerce Environment
• HTTP/XML is a very popular data exchange approach in B2B environment.
• You can use ASP, JSP or Servlet in Server side to read/write XML format data from/to any kind of Client.
• The client can be an application sit at another Server and a generic GUI application.
XML Progamming - 85 © Thomas Lee, 2000-2001
XML used in eCommerce Environment
• How to send XML data via Http/Post/Get method
• VB– Using OpenURL method provides by Inet COM
object to mimic Http/Post/Get method
• Java– Using URL to mimic Http/Post /Get to send request
in XML format as well as receive response in XML format.
XML Progamming - 86 © Thomas Lee, 2000-2001
XML used in eCommerce Environment
• VB – Open Project\Components
– Select Microsoft Internet Transfer Control 6.0
COM Object.
– Drag this COM Icon from ToolBox onto your form
– Implement the following codes
URLString = szBaseURL + "?FUNCTION=GETSPECIALITYLIST"
getResult URLString, xmlObj
Private Sub getResult(ByVal sURL As String, obj As CXMLParser)
szReturnedXML = Inet1.OpenURL(sURL)
xmlObj.XMLString = szReturnedXML
End Sub
Dom Object
XML Progamming - 87 © Thomas Lee, 2000-2001
XML used in eCommerce Environment
• Java– Make sure
import java.net.*;
– Put the following codes in your send methodString mResponse;
String request;
request= “…….”; //request string in XML format
mResponse ="";
DataInputStream dis = null;
Properties pro = new Properties();
pro.put(”RequestXML", request) ;
HttpURLConnection connection=null;
XML Progamming - 88 © Thomas Lee, 2000-2001
XML used in eCommerce Environment
try {
msUrl = “http://hostIpAddress:port/……/Test.asp?”;
mTheServer = new URL(msUrl);
connection = (HttpURLConnection) mTheServer.openConnection();
connection.setDoOutput(true);
connection.setUseCaches(false);
// Set Post Method and send Post Message
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
Set request method and content-type
XML Progamming - 89 © Thomas Lee, 2000-2001
XML used in eCommerce Environment
DataOutputStream out =
new DataOutputStream(connection.getOutputStream());
String argString = toEncodedString(pro);
out.writeBytes(argString);
out.flush();
out.close();
// Get Response
mResponse = readData(connection);
}
} Encode request string and send it toserver.
Read Response back(XML format)and use SAX or DOM to parse it
XML Progamming - 90 © Thomas Lee, 2000-2001
XML used in eCommerce Environment
toEncodedString Methodprivate String toEncodedString(Properties args) {
StringBuffer buf = new StringBuffer(1);
Enumeration names = args.propertyNames();
while(names.hasMoreElements()) {
String name = (String)names.nextElement();
String value = args.getProperty(name);
buf.append(URLEncoder.encode(name)+"=" +
URLEncoder.encode(value));
if(names.hasMoreElements())
buf.append("&");
}
return buf.toString();
}
XML Progamming - 91 © Thomas Lee, 2000-2001
XML used in eCommerce Environment
readData Methodprivate String readData(URLConnection connection)
{ Object content;
BufferedReader buffReader = null;
// Read upto 1024 characters or EOF from the return reponse
char[] cInputData;
String sReponse = "";
try {
content = connection.getContent(); if (content instanceof InputStream)
{
buffReader =
new BufferedReader(new InputStreamReader( (InputStream)content) );
} // When Input stream not null
XML Progamming - 92 © Thomas Lee, 2000-2001
XML used in eCommerce Environment
readData MethodDataInputStream dis = new
DataInputStream(connection.getInputStream());
String theLine;
if (dis != null) {
while ((theLine = dis.readLine()) != null)
{
sReponse = sReponse + theLine;
}}
}
catch (IOException e) {……. }
return sReponse;
XML Progamming - 93 © Thomas Lee, 2000-2001
XML used in eCommerce Environment
readData MethodDataInputStream dis = new
DataInputStream(connection.getInputStream());
String theLine;
if (dis != null) {
while ((theLine = dis.readLine()) != null)
{
sReponse = sReponse + theLine;
}}
}
catch (IOException e) {……. }
return sReponse;
XML Progamming - 94 © Thomas Lee, 2000-2001
Recommended