Concepts and Implementation

Slides:



Advertisements
Similar presentations
XML: Extensible Markup Language
Advertisements

XML & Data Structures for the Internet Yingcai Xiao.
1 CP3024 Lecture 9 XML revisited, XSL, XSLT, XPath, XSL Formatting Objects.
XML Technologies and Applications Rajshekhar Sunderraman Department of Computer Science Georgia State University Atlanta, GA 30302
XSL Transformations Transforming XML document into other (XML) documents 1XSL Transformations.
C# The new language for Updated by Pavel Ježek © University of Linz, Institute for System Software, 2004 published under the Microsoft Curriculum License.
.NET and XML (or XML in.NET) David Oguns Matt Harding.
XML.NET Concepts and Implementation Badar Gillani.
XML Fundementals XML vs.. HTML XML vs.. HTML XML Document (elements vs. attributes) XML Document (elements vs. attributes) XML and RDBMS XML and RDBMS.
XML Anisha K J Jerrin Thomas. Outline  Introduction  Structure of an XML Page  Well-formed & Valid XML Documents  DTD – Elements, Attributes, Entities.
Lecture 6 of Advanced Databases XML Schema, Querying & Transformation Instructor: Mr.Ahmed Al Astal.
XML for E-commerce III Helena Ahonen-Myka. In this part... n Transforming XML n Traversing XML n Web publishing frameworks.
Presentation XML. NET SEMINAR By: Siddhant Ahuja (SID)
XSLT for Data Manipulation By: April Fleming. What We Will Cover The What, Why, When, and How of XSLT What tools you will need to get started A sample.
XML and its applications: 4. Processing XML using PHP.
ASP.NET and XML Presented By: Shravan S. Mylavarapu 1.
School of Computing and Management Sciences © Sheffield Hallam University To understand the Oracle XML notes you need to have an understanding of all these.
XP 1 CREATING AN XML DOCUMENT. XP 2 INTRODUCING XML XML stands for Extensible Markup Language. A markup language specifies the structure and content of.
XP New Perspectives on XML, 2 nd Edition Tutorial 10 1 WORKING WITH THE DOCUMENT OBJECT MODEL TUTORIAL 10.
Extensible Markup and Beyond
Extending System.Xml Ted Neward
 XML is designed to describe data and to focus on what data is. HTML is designed to display data and to focus on how data looks.  XML is created to structure,
Intro. to XML & XML DB Bun Yue Professor, CS/CIS UHCL.
 2004 Prentice Hall, Inc. All rights reserved. 1 Chapter 34 - Case Study: Active Server Pages and XML Outline 34.1 Introduction 34.2 Setup and Message.
XML DOM Functionality in.NET DSK Chakravarthy
CITA 330 Section 6 XSLT. Transforming XML Documents to XHTML Documents XSLT is an XML dialect which is declared under namespace "
XML Part 2 Josh Steele CS 6704, Spring XML Part 2 XSL/XSLT –Structure Revisited –Definition –Example –Components XML’s Linking Languages XML’s Uses.
XSLT Kanda Runapongsa Dept. of Computer Engineering Khon Kaen University.
Lecture 11 XSL Transformations (part 1: Introduction)
DAT 379 XML Today And Tomorrow Mark Fussell Lead Program Manager Microsoft Corporation.
Module 7: Accessing Data by Using ADO.NET
1 Introduction  Extensible Markup Language (XML) –Uses tags to describe the structure of a document –Simplifies the process of sharing information –Extensible.
Accessing Data Using XML CHAPTER NINE Matakuliah: T0063 – Pemrograman Visual Tahun: 2009.
CS 157B: Database Management Systems II February 11 Class Meeting Department of Computer Science San Jose State University Spring 2013 Instructor: Ron.
COMP9321 Web Application Engineering Semester 2, 2015 Dr. Amin Beheshti Service Oriented Computing Group, CSE, UNSW Australia Week 4 1COMP9321, 15s2, Week.
Web Technologies Lecture 4 XML and XHTML. XML Extensible Markup Language Set of rules for encoding a document in a format readable – By humans, and –
.NET and XML (or XML in.NET) Matt Harding David Oguns.
Module 3: Working with Local Data. Overview Using DataSets Using XML Using SQL Server CE.
C Copyright © 2011, Oracle and/or its affiliates. All rights reserved. Introduction to XML Standards.
Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved Chapter 7 Representing Web Data:
CHAPTER NINE Accessing Data Using XML. McGraw Hill/Irwin ©2002 by The McGraw-Hill Companies, Inc. All rights reserved Introduction The eXtensible.
XML Extensible Markup Language
XML Schema – XSLT Week 8 Web site:
XSLT, XML Schema, and XPath Matt McClelland. Introduction XML Schema ▫Defines the content and structure of XML data. XSLT ▫Used to transform XML documents.
I Copyright © 2004, Oracle. All rights reserved. Introduction.
1 XSLT XSLT (extensible stylesheet language – transforms ) is another language to process XML documents. Originally intended as a presentation language:
XML: Extensible Markup Language Abeiku Duncan Leslie Salami Anthony Mensah-Kumah Michelle Amarteifio Joseph Owusu-Badu.
1 Introduction to XML Babak Esfandiari. 2 What is XML? introduced by W3C in 98 Stands for eXtensible Markup Language it is more general than HTML, but.
XSLT: The XML transformation language
Product Training Program
XML for .NET Session 1 Introduction to XML Introduction to XSLT
XML: Extensible Markup Language
XML Introduction Bill Jerome.
Unit 4 Representing Web Data: XML
Fast Train Computer School
Displaying XML Data with XSLT
Querying and Transforming XML Data
XML in Web Technologies
Extensible Markup Language XML
Data Modeling II XML Schema & JAXB Marc Dumontier May 4, 2004
Database Processing with XML
ACG 4401 XSLT Extensible Stylesheet Language for Transformations
Chapter 7 Representing Web Data: XML
Processing XML.
XML Data Introduction, Well-formed XML.
Applying eXtensible Style Sheets (XSL)
Chapter 13 XML Yingcai Xiao.
Web Development Using ASP .NET
04 | Data Acess Technologies
XML and its applications: 4. Processing XML using PHP
Presentation transcript:

Concepts and Implementation XML .NET Concepts and Implementation

Agenda Section – I Section – II XML Technology Why XML XML Skeleton Uses of XML General Schema Example Section – II XML in .NET Framework XML.NET Architecture Namespaces and Classes Hierarchy XmlReader Class XmlWriter Class XmlDocument Class System.Xml.Xsl Sytem.Xml.Xpath XML and ADO.NET XML and .NET Services

XML Technology Derived from SGML (Standard Generalized Markup Language) Text-based format Describes document structures using markup tags Useful for describing document formats for Web It is also useful for describing both structured as well as semi-structured data. Text-based format means that one can read and edit an xml document using standard text editing tools

Why XML? Platform-independent Extensible: Can be run over any operating System Can be processed using any programming language Extensible: No fixed vocabulary Flexible, change the structure by adding new tags Supports Global implementation being fully Unicode No emphasis on display and rendering the XML document

XML Skeleton Syntax similar to HTML XML Infoset Start tag <start> end tag </start> Case sensitive White spaces are preserved Elements must be properly nested XML Infoset Information items which are abstract representation of components of an xml document Up to 11 information items including Document, element, attribute, processing instructions etc.

Skeleton Schema Languages XML APIs Used to describe the structure and content of xml document During document interchange describes the contract between the producer and consumer application DTDs, XDR(Xml Data-Reduced), XSD(Xml Schema Definition) XML APIs Tree-model API – (full tree in memory) XmlDocument Class in .NET, DOM, SAX(Simple Api for Xml) Cursor-based API – lens on one node at a time XPathNavigator Class in .NET (only required fields in mem.) XmlCursor class from BEA's XMLBeans toolkit Streaming API SAX, XMLPULL, Object to XML Mapping API include JAXB, the .NET Framework's XmlSerializer and Castor.

Skeleton XML Query XML Transformation In some cases data extraction from XML documents through available APIs is difficult or all of the data can not be extracted. XPath, XQuery XML Transformation XSLT is the primary transformation tool There are various vendor tools available for transforming XML to HTML, PDF, WORD, RTF etc.

Uses of XML Traditional data processing Document-driven programming XML encodes the data for a program to process Document-driven programming XML documents are containers that build interfaces and applications from existing components Archiving Foundation for document-driven programming, where the customized version of a component is saved (archived) so it can be used later Binding DTD or schema that defines an XML data structure is used to automatically generate a significant portion of the application that will eventually process that data

Schema Anatomy of XML document

<?xml version="1.0" encoding="ISO-8859-1"?> <?xml-stylesheet href="test_xml.xsl" type="text/xsl"?> <?cocoon-process type="xslt"?> <% String url ="jdbc:oracle:thin:@goedel.newcs.uwindsor.ca:1521:CS01"; Connection connect= null; ResultSet result = null; int user=1; String query="select * from personal"; try{ Class.forName("oracle.jdbc.driver.OracleDriver"); connect = DriverManager.getConnection(url,user,pw); java.sql.Statement stmt = connect.createStatement(); result=stmt.executeQuery(query); } catch (Exception ex) { ex.printStackTrace(); %> out.println("<breakfast-menu>"); while(result.next()){ out.println("<food>"); out.println("<name>"+result.getString(“name”)+"</name>"); out.println("<price>"+result.getString(“prices")+"</price>"); out.println("<description>"+result.getString(“detail")+"</description>"); out.println("<calories>"+result.getString(“cal")+"</calories>"); out.println("</food>"); } out.println("</breakfast-menu>”);

Section-II Coverage XML in .NET Framework XML.NET Architecture Namespaces and Classes Hierarchy XmlReader Class XmlWriter Class XmlDocument Class System.Xml.Xsl Sytem.Xml.XPath

XML in .NET Framework

XML.NET Architecture XML is extensible in the .NET Framework (extending the existing classes) In the .NET Framework XML has a pluggabble architecture. Pluggable ~ abstrract classes can be easily substituted Pluggable ~ Data can be streamed between components and new components can be inserted that can alter the processing of the document

Pluggable Architecture Developer can create new classes by extending the existing ones Can introduce new features and thus changes the behavior of existing ones e.g. create MyXmlTextReader extending the XmlTextReader class which converts an attribute-centric document to an element-centric document

XML.NET Classes & Namespaces The Framework has several XML classes that allow working with XML documents and data These classes are the core elements of .NET Framework Most of the XML classes are contained in the System.Xml namespace. The term namespace refers to a logical grouping of the classes designed to implement a specific functionality.

System.Xml.Serialization Hierarchy XMlWriter XmlReader XmlNavigator XmlAttribute XmlElement XmlDocument System.Xml Namespace System.Xml Schema System.Xml .Xsl System.Xml.XPath System.Xml.Serialization

XML Parsing General Parsing Models Parsing in .NET Pull Model : forward only Push Model: forward only Document Object Model (DOM) Parsing in .NET Pull Model DOM

XmlReader Class XmlReader XmlTextReader MoveTo() Read() XmlValidatingReader XmlNodeReader XmlRedare – Abstract Class XmlTextReader – Reads text based stream, non-cached, read-only XmlNodeReader – Reads in memory DOM tree XmlValidatingReader – validates with DTD, XDR XSD schemas

XmlReader Example XmlReader reader; Reader = new XmlTextReader(“test.xml”); While(reader.Read()){ /* Your processing code here */ }

Use of XmlReader using C# <%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.SqlClient" %> <%@ Import Namespace="System.Xml" %> <script language="C#" runat="server"> void Page_Load(Object s, EventArgs e) { SqlConnection con = new sqlConnection(ConfigurationSettings.AppSettings["con"]); SqlCommand cmd = new SqlCommand("SELECT * FROM Employees FOR XML AUTO, ELEMENTS, XMLDATA",con); con.Open(); XmlReader xr = cmd.ExecuteXmlReader(); while(xr.Read()) { Response.Write(Server.HtmlEncode(xr.ReadOuterXml()).ToString() + “<br>"); } con.Close(); </script>

VB Script for XmlReader Imports System Imports System.Xml Public Class Form1 Inherits System.Windows.Forms.Form Private Const filename As String = "c:\books.xml" public Shared Sub Main(] Dim reader As XmlTextReader = Nothing Dim strOut As String Try 'Point the reader to the data file and ignore all whitespaces reader = New XmlTextReader(filename) reader.WhitespaceHandling = WhitespaceHandling.None 'Parse the file and display each of the nodes. Do While (reader.Read()) Select Case reader.NodeType Case XmlNodeType.Element strout = strOut + "<" +reader.Name If reader.HasAttributes Then While reader.MoveToNextAttribute() strOut = strout + "" + reader.Name +" '"+ End While End If strOut = strOut + ">" Case XmlNodeType.Text strOut= strOut + readerValue Case XmlNodeType.EndElement strOut = strOut + "</" + reader.Name strOut = strPut + ">" +vbCrLf End Select Loop VB Script for XmlReader

XmlWriter Class XmlWriter XmlTextWriter MoveTo() XmlNodeWriter Read() XmlWriter writer = new XmlTextWriter(); writer.WriteStartDocument(); Writer.WriteStartElement(“name”, “Badar”);

XmlWriter Class Overview

VB code for XmlWriter Imports System Imports System.IO Imports System.Xml Public Class From1 Inherits System.Windows.Forms.Form Private Sub Button1.Click(ByVal sender As System.Object, ByVal e As System.) DisplayXML() End Sub Private Sub DisplayXML() Dim filename As String = "c:\newbook.xml" Dim wrt As XmlTextwriter = New XmlTextWriter(filename Nothing) wrt.Formatting = Formatting.Indented wrt.WriteStartDocument(True) wrt.WriteStartComment("Catalog fragment") wrt.WriteStartElement("books") wrt.WriteStartElement("book") wrt.WriteAttributeString(“gener", "", “technology) wrt.WriteAttributeString("publicationdate", "", 1995) wrt.WriteAttributeString("ISBN", "", "0-670-77289-5) wrt.WriteElementString("title", "", "The Road Ahead") wrt.WriteStartElement("author", "") wrt.WriteElementString("first-name", "Bill") wrt.WriteElementString("last-name", "Gates") wrt.WriteEndElement() wrt.WriteElementString("price", "29.95") wrt.WriteEndDocument() wrt.Flush() wrt.Close() Dim doc As New XmlDocument() doc.PreserveWhotesapces = True doc.Load(filename) TextBox1.Text = doc.InnerXml End Class VB code for XmlWriter

Output in the textbox

C# code for XmlWriter namespace WriteXML { using System; using System.Xml; public class BankAccount { private const string m_strFileName = "c:\\account.xml"; public static void Main() //Make sure M is in uppercase in Main() above XmlTextWriter bankWriter = null; bankWriter = new XmlTextWriter (m_strFileName, null); try bankWriter.WriteStartDocument(); bankWriter.WriteStartElement("", "BankAccount", ""); bankWriter.WriteStartElement("", "Number", ""); bankWriter.WriteString("1234"); bankWriter.WriteEndElement(); bankWriter.WriteStartElement("", "Type", ""); bankWriter.WriteString("Checking"); bankWriter.WriteStartElement("", "Balance", ""); bankWriter.WriteString("25382.20"); bankWriter.Flush(); } catch(Exception e) Console.WriteLine("Exception: {0}", e.ToString()); finally if (bankWriter != null) { bankWriter.Close(); }

XmlDocument (DOM) XmlDocument XmlNodeList XmlNamedNodeMap XmlNodeList – Collection of Different Xml Nodes XmlNamedNodeMap – collection of Attributes Methods Laod LoadXml Save

VB code for XmlDocument Imports System.Xml Public Class Form1 Inherits System.Window.Forms.Form Private Sub Button1 Click(ByVal sender As System.Object, ByVal e As System. Object) 'Create a new XMlDocument Class and use the Load method to Load file Dim myXmlDocument As XmlDocument = New XmlDocument() myXmlDocument.Load("c:\books.xml") 'Use the XmlNode Object returned by the DocumentElement property 'of the XmlDocument to manipulate an XML node Dim node As XmlNode node = myXmlDocument.DocumentElement 'Now we find all the price nodes and then double the value for each book For Each node In myXmlDocumnet.SelectNode("//price") Dim price As Decimal price = System.Decimal.Parse(node.InnerText) 'Doubling the price Dim newprice As String newprice = CType(price * 2, Decimal).ToString("#.00") 'Writing change to the document node.InnerText = newprice Next 'here we save the altered XML to new file called books2.xml muXmlDocument.Save("c:\books2.xml")

C# code for XmlDocument using System; using System.Xml; namespace PavelTsekov { class MainClass { XmlDocument xmldoc; XmlNode xmlnode; XmlElement xmlelem; XmlElement xmlelem2; XmlText xmltext; static void Main(string[] args) { MainClass app=new MainClass(); } public MainClass() //constructor { xmldoc=new XmlDocument(); //let's add the XML declaration section xmlnode=xmldoc.CreateNode(XmlNodeType.XmlDeclaration,"",""); xmldoc.AppendChild(xmlnode); //let's add the root element xmlelem=xmldoc.CreateElement("","ROOT",""); xmltext=xmldoc.CreateTextNode("This is the text of the root element"); xmlelem.AppendChild(xmltext); xmldoc.AppendChild(xmlelem); //let's add another element (child of the root) xmlelem2=xmldoc.CreateElement("","SampleElement",""); xmltext=xmldoc.CreateTextNode("The text of the sample element"); xmlelem2.AppendChild(xmltext); xmldoc.ChildNodes.Item(1).AppendChild(xmlelem2); //let's try to save the XML document in a file: C:\pavel.xml try { xmldoc.Save("c:\pavel.xml"); //I've chosen the c:\ for the resulting file pavel.xml } catch (Exception e) { Console.WriteLine(e.Message); Console.ReadLine(); C# code for XmlDocument

XML Transformation System.Xml.Xsl XslTransform – Transforms XML data using XSLT stylesheets XsltArgumentList – Allows parameters and extension objects to be invoked from within the stylesheet Xsltexception – Returns information about the last exception thrown while processing an XSL transform

XslTransform Class

XslTranform book.xsl ============================================================================================================== <xsl:stylesheet xmlns:xsl=http://www.w3.org/1999/XSL/Transform version=“1.0”> <xsl:template match="bookstore"/> <xsl:template match=“/"> <HTML> <BODY> <TBALE BORDER="2"> <TR> <TD>ISBN</TD> <TD>Title</TD> <TD>Price</TD> </TR> <xsl:apply-template select="book"> <xsl:sort select="@ISBN"/> </xsl:apply-tempalet> <xsl:for-each select=“book”> <TD><xsl:value-of select="@ISBN"/></TD> <TD><xsl:value-of select="title"/></TD> <TD><xsl:value-of select="price"/></TD> </xsl:for-each> </TABLE> </BODY> </HTML> </xsl:template> </xsl:stylesheet>

VB code for XslTransform Imports System Imports System.IO Imports System.Xml Imports System.Xml.XPath Imports System.Xml.Xsl Imports System.Net Public Class Form1 Inherits System.Windows.Forms.Form Dim filename As String = "c:\books.xml" Dim stylesheet As String = "c:\book.xsl" Private Sub Button1_click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handle Button1.Click Dim xslt As XslTransform = New XslTransform() xslt.Load(stylesheet) Dim doc As XPathDocument = New XPtahDocument(filename) Dim writer As XmlTextWriter = New XmlTextWriter("c:\sortedbooks.html", Nothing) xslt.Transform(doc, Nothing, writer) writer.Close() End Sub End Class

Output in HTML

Xpath Query in .NET Used to specify query expressions to locate nodes in XML document Used in XSLT stylesheets to locate and apply transformation to specific nodes in an XML document Used in DOM code to locate and process specific nodes in an XML document

System.Xml.XPath Key Classes XPathDocument XpathNavigator XPathNodeIterator XPathExpression

Code of the XPath Query Private Sub Button1_click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim PlatoBookList As XmlNodeList Dim PlatoBook As XmlNode Dim strOut As String PlatoBookList =xmldoc.SelectNOdes("//last-name[.='Plato']/ancestor::node()/title") strOut = strOut +"Books written by Plato:"+vbCrLf strOut = strOut +"***********************"+vbCrLf For Each PlatoBook In PaltoBookList strOut = strOut +PlatoBook.InnerText.vbCrLf Next MsgBox(strOut) End Sub

Query Output

XML and ADO.NET In .NET Framework tight integration has been introduced between XML classes and ADO.NET The DataSet components are able to read and write XML using XmlRead and XmlWrite Classes There is a synchronization between XmlDocument and DataSet, which enables automatic update XmlDataDocument (extension of XmlDocument) provides a bridge between relational and hierarchical data

References Book Employing XML in .NET Framework http://msdn.microsoft.com/library/default.asp?url=/nhp/default.asp?contentid=28000438 XML – Module 1: Introduction to the Core .Net Framework XML Namesapces and Classes by Bill Lange (Online Seminars) http://msdn.microsoft.com/library/default.asp?url=/seminar/mmcfeed/mmcdisplayfeed.asp?lang=en&product=103337&audience=100402 by Roger Wolter Microsoft Corporation http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnwebsrv/html/webservbasics.asp