Presentation is loading. Please wait.

Presentation is loading. Please wait.

XML Programming Thomas Lee

Similar presentations


Presentation on theme: "XML Programming Thomas Lee"— Presentation transcript:

1 XML Programming Thomas Lee E-Mail: thomas_c_lee@yahoo.com

2 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.

3 XML Progamming - 3 © Thomas Lee, 2000-2001 Course Outline XML Overview SAX DOM Lab 1 Lab 2 Lab 3

4 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

5 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 !!!

6 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

7 XML Progamming - 7 © Thomas Lee, 2000-2001 Logistics Parking Permit Rest Room Café Tear

8 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.

9 XML Progamming - 9 © Thomas Lee, 2000-2001 Attendee Introductions Your Name Background Why you take this course ? What you expect from this course ?

10 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%.

11 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.

12 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.

13 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

14 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.

15 XML Progamming - 15 © Thomas Lee, 2000-2001 XML DTD HTML Resources XML Data Store Application XSL XPL HTML/CSS Display and Reporting XLL XML Data Types Data Transfer Definition and Structure Link to other resources XML Schema XML Technologies

16 XML Progamming - 16 © Thomas Lee, 2000-2001 Java and XML XML is an essential component in the Java 2 Platform, Enterprise Edition (J2EE TM ) 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 JavaBeans TM (EJB TM ) 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 Pages TM technology. Currently, JavaServer Pages technology can be used to generate and consume XML between n- tier servers or between server and client.

17 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.

18 XML Progamming - 18 © Thomas Lee, 2000-2001 Quick Review of XML Background XML Components –Header »Instruction e.g. »Document Type Declaration e.g –Content »Root Element, Data Element e.g ……… »Element Attributes e.g »References e.g. &onedayPrice »Unparsed Data e.g. s > ]]>

19 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

20 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. … … Example of legal XML – Adam Smith General Manager 42

21 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 John Smith is an advocate for XML Illegal XML John XML provides a data bus …

22 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: or Illegal: XML tags are case sensitive. are different

23 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: is equivalent to Illegal:

24 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. Microsoft –Document Type Definition (DTD): This is used to define a grammar for the tags and attributes. This syntax is supported, but deprecated by Microsoft. 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.

25 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 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

26 XML Progamming - 26 © Thomas Lee, 2000-2001 Quick Review of XML Background Sample of DTD ( Embedded) <!DOCTYPE Course [ ]> XML Programming $275 AIT March 17,2001

27 XML Progamming - 27 © Thomas Lee, 2000-2001 Quick Review of XML Background Sample of DTD (Reference) Demo1.dtd <!DOCTYPE Course [ ]>

28 XML Progamming - 28 © Thomas Lee, 2000-2001 Quick Review of XML Background Sample of DTD (Reference) ] > XML Programming $275 AIT March 17,2001

29 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

30 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.

31 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 http://www.w3org/TR/REC-xml-names

32 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

33 XML Progamming - 33 © Thomas Lee, 2000-2001 Quick Review of XML Background XSL and XML Sample greeting.xml Hello World! greeting.xsl

34 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

35 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

36 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

37 XML Progamming - 37 © Thomas Lee, 2000-2001 Quick Review of XML Background SAX/DOM

38 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.

39 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 & validationXML editing & validation »Schema/DTD editing & validationSchema/DTD editing & validation »XSL editing & transformationXSL editing & transformation »Reference: http://www.xmlspy.com

40 XML Progamming - 40 © Thomas Lee, 2000-2001 SAX Programming In Java

41 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

42 XML Progamming - 42 © Thomas Lee, 2000-2001 SAX Programming Guidelines –(4)Prepare a XML document –(5)Write Programs to parse XML document.

43 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

44 XML Progamming - 44 © Thomas Lee, 2000-2001 SAX Programming SAX Related package org.xml.sax org.xml.sax.helpers

45 XML Progamming - 45 © Thomas Lee, 2000-2001 SAX Programming-SAXDemo1.java Import necessary libraries java.io.* org.xml.sax.* java.util.*; javax.xml.parsers.SAXParserFactory javax.xml.parsers.ParserConfigurationException javax.xml.parsers.SAXParser Parser API Interface

46 XML Progamming - 46 © Thomas Lee, 2000-2001 SAX Programming-SAXDemo1.java org.xml.sax : - Defines the SAX interfacesorg.xml.sax 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

47 XML Progamming - 47 © Thomas Lee, 2000-2001 SAX Programming-SAXDemo1.java Contents 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

48 XML Progamming - 48 © Thomas Lee, 2000-2001 SAX Programming-SAXDemo1.java Contents in org.xml.sax.helpers package Bold for SAX 2.0 Classes AttributeListImpl AttributesImpl DefaultHandler LocatorImpl NamespaceSupport ParserAdapter ParserFactory XMLFilterImpl XMLReaderAdapter XMLReaderFactory

49 XML Progamming - 49 © Thomas Lee, 2000-2001 SAX Programming-SAXDemo1.java Creating /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 DTD Validating Feature Create SAXParser Read from File Useful if we set validating to true

50 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

51 XML Progamming - 51 © Thomas Lee, 2000-2001 SAX Programming-SAXDemo1.java Implementing 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 ); }

52 XML Progamming - 52 © Thomas Lee, 2000-2001 SAX Programming-SAXDemo1.java Implementing ContentHandler Functions(2) public void endElement (String name) throws SAXException { } public void startDocument () throws SAXException { } public void endDocument () throws SAXException { }

53 XML Progamming - 53 © Thomas Lee, 2000-2001 SAX Programming-SAXDemo1.java Implementing 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

54 XML Progamming - 54 © Thomas Lee, 2000-2001 SAX Programming-SAXDemo1.java Implementing 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 { ….. }

55 XML Progamming - 55 © Thomas Lee, 2000-2001 SAX Programming-SAXDemo1.java Implementing ErrorHandler Functions Report the violation of a well-formedness constraint. public void fatalError (SAXParseException ferr) throws SAXParseException { throw ferr; }

56 XML Progamming - 56 © Thomas Lee, 2000-2001 SAX Programming-SAXDemo1.java Implementing Test Procedure public 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){….} } }

57 XML Progamming - 57 © Thomas Lee, 2000-2001 SAX Programming-SAXDemo1.java bulid.bat set 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 g LOCATOR SYS ID: file:E:/XMLClass/SAXDemo1/Demo0.xml Title: Introduction to XML Programming Price: $275 Instructor: AIT Date: null

58 XML Progamming - 58 © Thomas Lee, 2000-2001 SAX Programming-SAXDemo1.java Run 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!

59 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

60 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

61 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

62 XML Progamming - 62 © Thomas Lee, 2000-2001 DOM Programming In Java

63 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

64 XML Progamming - 64 © Thomas Lee, 2000-2001 DOM Programming-DomDemo3.java Processing Instruction TextComment EntityReferenceCDATASectionElement Document Type comment Processing Instruction Document (Root) Element Attributes EntitiesNotations childNodes DOM Model

65 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

66 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 tree Root Leftmost Right branch

67 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

68 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.

69 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

70 XML Progamming - 70 © Thomas Lee, 2000-2001 DOM Programming-DomDemo3.java EntityReference –A holder for aliased parsed text.

71 XML Progamming - 71 © Thomas Lee, 2000-2001 DOM Programming-DomDemo3.java Import Libraries import 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;

72 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

73 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

74 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

75 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

76 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 method This method provides the content inside a given Element name

77 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 object System.out.println("Title:" + oDemo.getElValue("Title")); System.out.println("Instructor:" + ……. } Catch(….){} Use this getElValue

78 XML Progamming - 78 © Thomas Lee, 2000-2001 DOM Programming In VB

79 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

80 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,……...

81 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 related work in VB, Please see CXMLParser.cls file for detail information

82 XML Progamming - 82 © Thomas Lee, 2000-2001 XML used in eCommerce Environment HTTP/XML

83 XML Progamming - 83 © Thomas Lee, 2000-2001 XML used in eCommerce Environment HTTP/XML

84 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.

85 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.

86 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

87 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 method String mResponse; String request; request= “…….”; //request string in XML format mResponse =""; DataInputStream dis = null; Properties pro = new Properties(); pro.put(”RequestXML", request) ; HttpURLConnection connection=null;

88 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

89 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 to server. Read Response back(XML format) and use SAX or DOM to parse it

90 XML Progamming - 90 © Thomas Lee, 2000-2001 XML used in eCommerce Environment toEncodedString Method private 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(); }

91 XML Progamming - 91 © Thomas Lee, 2000-2001 XML used in eCommerce Environment readData Method private 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

92 XML Progamming - 92 © Thomas Lee, 2000-2001 XML used in eCommerce Environment readData Method DataInputStream dis = new DataInputStream(connection.getInputStream()); String theLine; if (dis != null) { while ((theLine = dis.readLine()) != null) { sReponse = sReponse + theLine; }} } catch (IOException e) {…….} return sReponse;

93 XML Progamming - 93 © Thomas Lee, 2000-2001 XML used in eCommerce Environment readData Method DataInputStream dis = new DataInputStream(connection.getInputStream()); String theLine; if (dis != null) { while ((theLine = dis.readLine()) != null) { sReponse = sReponse + theLine; }} } catch (IOException e) {…….} return sReponse;

94 XML Progamming - 94 © Thomas Lee, 2000-2001


Download ppt "XML Programming Thomas Lee"

Similar presentations


Ads by Google