XML - PowerPoint PPT Presentation

1 / 74
About This Presentation
Title:

XML

Description:

May be grouped into an attribute group more later! Based on a simpleType , by reference or explicitly attribute name = 'age' type='integer' ... – PowerPoint PPT presentation

Number of Views:40
Avg rating:3.0/5.0
Slides: 75
Provided by: bartadep
Category:
Tags: xml | attribute

less

Transcript and Presenter's Notes

Title: XML


1
XML
  • eXtensible Markup Language

2
Objectives
  • Introduce XML Including
  • XML Documents Basics
  • XML Schema
  • XML Stylesheets Transformations (XMLS/T)
  • Explore the XML Support in .NET

3
Contents
  • Have a Look Back The pre-XML world
  • The XML Architecture
  • XML XML Document Basics
  • XML Schemata
  • Stylesheets Transformations
  • .NET Framework Support for XML
  • System.Xml and sub-namespaces

4
Looking Back
  • Tightly coupled systems and communication
  • Proprietary, closed protocols and methods
  • Data sharing between 3rd party solutions unwieldy
  • Non-extensible solutions

5
XML!
  • XML technologies introduced
  • XML 1.0 - Document Basics
  • XML Schemata
  • XSLT Style sheets and Transformations
  • .NET XML
  • The System.Xml Namespace

6
XML 1.0 - Document Basics
  • What is XML?
  • XML Tags and Tag Sets
  • Components of an XML Document
  • Document Instance
  • XML Document by Example
  • The XML Parser

7
What is XML? 1/2
  • Stands for Extensible Markup Language
  • Language specification for describing data
  • Syntax rules
  • Syntax Grammar for creating Document Type
    Definitions
  • Widely used and open standard
  • Defined by the World Wide Web Consortium (W3C)
  • http//www.w3.org/TR/2000/REC-xml-20001006

8
What is XML? 2/2
  • Designed for describing and interchanging data
  • Data is logically structured
  • Human readable, writeable and understandable text
    file!
  • Easy to Parse Easy to Read and Easy to Write!
  • Metadata
  • Data that describes data data with semantics
  • Looks like HTMLbut it isnt!
  • Uses tags to delimit data and create structure
  • Does not specify how to display the data

9
XML Tag-Sets
  • Begin with ltsomeTaggt and end with lt/someTaggt
  • Can have an empty element ltsomeTag /gt
  • Exceptions are
  • XML document declaration lt?xml ... ?gt
  • Comments lt!-- some comment --gt
  • The document type declaration
  • lt! DOCTYPE ... gt
  • Definition of document elements in an Internal
    DTD
  • lt!ELEMENT gt, lt!ATTLISTgt, etc
  • Promote logical structuring of documents and data
  • User definable
  • Create hierarchically nested structure

10
Components of an XML Document 1/3
  • XML Processing Instruction
  • Document Type Declaration
  • Document Instance

11
Components of an XML Document 2/3
  • XML Processing Instruction
  • lt?xml version 1.0 encoding UTF-8 ?gt
  • version information
  • encoding type UTF-8, UTF-16, ISO-10646-UCS-2,
    etc
  • standalone declaration indicates if there are
    external file references
  • Namespace declaration(s), Processing Instructions
    (for applications), etc

12
Components of an XML Document 3/3
  • Document Type Declaration. Two types
  • An Internal declaration
  • An External reference
  • Document Instance
  • This is the XML document instance
  • Read as the XML-ized data

lt!DOCTYPE CustomerOrder lt!-- internal DTD goes
here! --gt gt
lt!DOCTYPE CustomerOrder SYSTEM
"http//www.myco.com/CustOrder.dtd"gt
13
Document Instance The Markup
  • Document Root Element
  • Required if a document type declaration exists
  • Must have the same name as the declaration
  • Elements
  • Can contain other elements
  • Can have attributes assigned to them
  • May or may not have a value
  • Attributes
  • Properties that are assigned to elements
  • Provide additional element information

14
XML By Example A Document
lt?xml version 1.0 encoding UTF-8 ?gt lt!
DOCTYPE CustomerOrder SYSTEM http//www.myco.com
/dtd/order.dtd gt ltCustomerOrdergt ltCustomergt ltP
ersongt ltFNamegt Olaf lt/FNamegt ltLNamegt Smith
lt/LNamegt lt/Persongt ltAddress AddrType
shippinggt 91 Park So, New York, NY 10018
lt/Addressgt ltAddress AddrType
billinggt Hauptstrasse 55, D-81671
Munich lt/Addressgt lt/Customergt ltOrdersgt ltOrderN
ogt 10 lt/OrderNogt ltProductNogt 100
lt/ProductNogt ltProductNogt 200 lt/ProductNogt lt/Ord
ersgt lt!-- More ltCustomergts ...
--gt lt/CustomerOrdergt
15
XMLData DTD
lt!-- XML Data--gt ltagt ltbgt Some lt/bgt ltcgt 100
lt/cgt ltcgt 101 lt/cgt lt/agt
DTD
Not Valid!
lt!ELEMENT a (b, c?) gt lt!ELEMENT b (PCDATA)
gt lt!ELEMENT c (PCDATA) gt
lt!-- XML Data--gt ltagt ltbgt Some lt/bgt ltbgt
Thing lt/bgt lt/agt
Valid
16
Whats a DTD?
  • Document Type Definition (DTD)
  • Defines the syntax, grammar semantics
  • Defines the document structure
  • What Elements, Attributes, Entities, etc are
    permitted?
  • How are the document elements related
    structured?
  • Referenced by or defined in XML documents, but
    its not XML!
  • Enables validation of XML documents using an XML
    Parser
  • Can be referenced to by more than one XML
    document
  • DTDs may reference other DTDs

17
DTD By Diagram
CustomerOrder
Customer
Orders
Person
FName
LName
Orders
Orders
18
DTD By Example
  • http//www.myco.com/dtd/order.dtd

lt?xml version 1.0 encoding UTF-8
?gt lt!DOCTYPE CustomerOrder lt!ELEMENT
CustomerOrder (Customer, Orders) gt lt!ELEMENT
Customer (Person, Address) gt lt!ELEMENT Person
(FName, LName) gt lt!ELEMENT FName (PCDATA)
gt lt!ELEMENT LName (PCDATA) gt lt!ELEMENT Address
(PCDATA) gt lt!ATTLIST Address AddrType (
billing shipping home ) shipping
gt lt!ELEMENT Orders (OrderNo, ProductNo)
gt lt!ELEMENT OrderNo (PCDATA) gt lt!ELEMENT
ProductNo (PCDATA) gt gt
19
XML Parser in Action!
XML Schema Or DTD
XML Parser
XML Source Document
Validated XML Document
20
The XML Parser What is it?
  • Used to Process an XML Document
  • Reads, parses interprets the DTD and XML
    document
  • Performs substitutions, validation or additional
    processing
  • Knows the XML language rules and can determine
  • Is the document Well-Formed?
  • Is it Valid?
  • Creates a Document Object Model (DOM) of the
    instance
  • Provides programmatic access to the DOM or
    instance

21
What is the DOM?
  • DOM stands for Document Object Model
  • Programming interface for HTML XML documents
  • An in-memory representation of a document
  • Defines the document structure through an object
    model
  • Tree-view of a document
  • Nodes, elements and attributes, text elements,
    etc
  • W3C defined the DOM Level 1 and Level 2 Core
  • http//www.w3.org/TR/1998/REC-DOM-Level-1-19981001
    /
  • http//www.w3.org/TR/2000/REC-DOM-Level-2-Core-200
    01113/

22
Generating The DOM
lt?xml version1.0?gt XML Document
Parser
23
Where Do You Find XML Parsers?
  • Transparently built into XML enabled products
  • Internet Explorer, SQL Server 2000, etc
  • All over the Internet!
  • Microsoft XML Parser
  • http//msdn.microsoft.com/xml/general/xmlparser.as
    p
  • IBM/Apache Xerces
  • http//xml.apache.org
  • http//alphaworks.ibm.com

24
XML Schema
  • Whats a Schema?
  • Schema vs. DTDs
  • Datatypes Structure

25
XML Documents XML Schema
lt!-- XML Data--gt ltagt ltbgt Some lt/bgt ltcgt 100
lt/cgt ltcgt 101 lt/cgt lt/agt
lt!-- Some XML Schema --gt ltelement name a" gt
ltcomplexTypegt ltsequencegt ltelement nameb
typestring"
minOccurs1"/gt ltelement namec"
type"integer" maxOccurs"1" /gt
lt/sequencegt lt/complexTypegt lt/elementgt
Not Valid!
lt!-- XML Data--gt ltagt ltbgt Some lt/bgt ltbgt
Thing lt/bgt lt/agt
Valid
26
Whats a Schema?
  • Websters Collegiate Dictionary defines it as
  • A diagrammatic presentation a structured
    framework
  • The XML world defines it as
  • A structured framework for your XML Documents!
  • A definition language - with its own syntax
    grammar
  • A means to structure data and enhance it with
    semantics!
  • Best of all Its an alternative to the DTD!
  • Composed of two parts
  • Structure http//www.w3.org/TR/2001/REC-xmlschema
    -1-20010502/
  • Datatypes http//www.w3.org/TR/2001/REC-xmlschema
    -2-20010502/

27
Schema vs. DTDs
  • Both are XML document definition languages
  • Schemata are written using XML
  • Unlike DTDs, XML Schema are Extensible like
    XML!
  • More verbose than DTDs but easier to read write

28
Datatypes Structure
  • Defining datatypes
  • The simple or primitive datatypes
  • Based on (or derived) from the Schema datatypes
  • Complex types
  • Facets
  • Declaring data types
  • ltschemagt by example

29
XML Schema Datatypes
  • Two kinds of datatypes Built-in and User-defined
  • Built-in
  • Primitive Datatypes
  • string, double, recurringDuration, etc
  • Derived Datatypes
  • CDATA, integer, date, byte, etc
  • Derived from the primitive types
  • Example integer is derived from double
  • User-defined
  • Derived from built-in or other user-defined
    datatypes

30
The Simple Type ltsimpleTypegt
  • The Simplest Type Declaration
  • ltsimpleType name FirstName type string/gt
  • Based on a primitive or the derived built-in
    datatypes
  • Cannot contain sub-elements or attributes
  • Can declare constraining properties (facets)
  • minLength, maxLength, Length, etc
  • May be used as base type of a complexType

31
The Complex Type ltcomplexTypegt
  • Used to define a new complex type
  • May be based on simple or existing complexTypes
  • May declare elements or element references
  • ltelement name... type ... /gt
  • ltelement ref.../gt
  • May declare attributes or reference attribute
    groups
  • ltattribute name... type.../gt
  • ltattributeGroup ref ... /gt

32
Defining a complexType By Example
ltcomplexType name Customergt ltsequencegt
ltelement name Person typeName /gt
ltelement name Address typeAddress /gt
lt/sequencegtlt/complexTypegt ltcomplexType
nameAddressgt ltsequencegt ltelement
nameStreet typestring /gt ltelement
nameCity typestring /gt ltelement
nameState typeState_Region /gt ltelement
namePostalCode typestring /gt ltelement
nameCountry typestring /gt lt/sequencegt
lt!-- AddrType attribute not shown
--gt lt/complexTypegt
33
More Complex Types
  • Derivation
  • simpleContent complexContent
  • Extension Restriction (well see some of this)
  • Substitution Groups
  • Abstract Elements and Types

34
The Many Facets of a Datatype!
  • http//www.w3.org/TR/2001/REC-xmlschema-2-20010502
    /
  • A way to constrain datatypes
  • Constrain the value space of a datatype
  • Specify optional properties
  • Examples of Constraining Facets
  • precision, minLength,enumeration, ...

ltsimpleType nameFirstNamegt ltrestriction base
stringgt ltminLength value 0
/gt ltmaxLength value 25 /gt lt/restrictiongt
lt/simpleTypegt
35
Declaring ltelementgt Elements
  • Elements are declared using the ltelementgt tag
  • Based on either a simple or complex type
  • May contain simple or other complex types
  • May reference an existing element

ltelement name FirstName type string /gt
ltelement name Address type AddressType /gt
ltelement name Orders gt ltcomplexTypegt
ltsequencegt ltelement name OrderNo type
string /gt ltelement name ProductNo
type string /gt lt/sequencegt
lt/complexTypegt lt/elementgt
ltelement ref FirstName /gt
36
Declaring Attributes
  • Declared using ltattributegt tag
  • Value pairs
  • Can only be assigned to ltcomplexTypegt types
  • May be grouped into an attribute group more
    later!
  • Based on a ltsimpleTypegt, by reference or
    explicitly

ltattribute name age typeinteger /gt lt!-- OR
--gt ltattribute name age gt ltsimpleTypegt
ltrestriction baseintegergt ltmaxLength
3/gt lt/restrictiongt lt/simpleTypegtlt/attribu
tegt
37
Declaring Attribute Groups 1/2
  • Way to group related attributes together
  • Promotes logical organization
  • Encourages reuse defined once, referenced many
    times
  • Facilitates maintenance
  • Improves Schema readability
  • Must be unique within an XML Schema
  • Referenced from complexType definitions

38
Declaring Attribute Groups 2/2
lt!-- Define the unique group --gtltattributeGroup
name CreditCardInfo gt ltattribute name
CardNumber type integer use
required /gt ltattribute name
ExpirationDate type date use
required /gt ltattribute name CardHolder
type FullName use required
/gtlt/attributeGroupgt lt!-- Then you can
reference it from a complexType --gtltcomplexType
name CreditInformation gt ltattributeGroup
ref CreditCardInfo /gtlt/complexTypegt
39
Schema Namespaces
  • Equivalent to XML namespaces
  • http//www.w3.org/TR/1999/REC-xml-names-19990114/
  • Used to qualify schema elements
  • ltschemagt must itself be qualified with the schema
    namespace
  • Namespace may have a namespace prefix for the
    schema
  • Prefix qualifies elements belonging to the
    targetNamespace

ltschema xmlns http//www.w3.org/2001/XMLSchema
gt
ltschema xmlns http//www.w3.org/2001/XML
Schema xmlnsCO http//www.MyCompany.com/Sc
hema gt
40
ltschemagt targetNamespace Attribute
  • ltschemagt targetNamespace attribute
  • Declares the namespace of the current schema
  • This must be a universally unique Universal
    Resource Identifier (URI)
  • Helps the parser differentiate type definitions
  • Used during schema validation
  • Differentiates differing schema vocabularies in
    the schema
  • targetNamespacenamespace_prefix some_URI...
  • Should match the schema namespace declaration
  • Example
  • targetNamespaceCO "http//www.myCo.com/CO"

41
XML ltschemagt By Example
lt?xml version"1.0" encoding"UTF-8"?gt ltxsdschema
targetNamespace http//www.myCo.com/CO xml
nsCOhttp//www.myCo.com/CO xmlnsxsd"http/
/www.w3.org/2001/XMLSchema" elementFormDefault
"qualified attributeFormDefault"qualified e
lementFormDefault"qualified"gt lt!-- Declare
the root element of our schema --gt
ltxsdelement name"CustomerOrder"
type"COCustomerOrder"/gt lt!-- Further
Definitions declarations not shown
--gtlt/xsdschemagt
42
Follow the Yellow Brick XPath
  • Specification found at
  • http//www.w3.org/TR/1999/REC-xpath-19991116
  • Language used to address parts of an XML document
  • Permits selection of nodes in an XML document
  • Uses a path notations like with URLs
  • Absolute paths /CustomerOrder/Orders
  • Relative paths Orders

43
Roadmap To Selection
  • Location Syntax
  • axisnode_test predicate
  • Location Paths
  • Axis Defines from where to start navigating
  • parent, child, ancestor, attribute, / (the
    document), etc
  • Node test Selects one or more nodes
  • By tag name, node selector or wildcard ()
  • node( ), text( ), comment( ), etc
  • Predicates Optional function or expression
    enclosed in ...
  • position( ), count( ), etc
  • Example /Address _at_AddrTypebilling

44
Taking XPath Shortcuts
  • Abbreviated Syntax exists
  • The following are equivalent
  • OrderNoposition1/ProductNoposition3 Order
    No1/ProductNo3
  • .. instead of parentnode()
  • . instead selfnode()
  • // instead of /descendant-or-selfnode()/

45
Operators
  • To select an attribute value use _at_
  • CustomerOrder/Customer/Address_at_AddrType
  • To select the value of an element use
  • CustomerOrder/Orders/ProductNo1ProductNo
  • Can compare objects arithmetically
  • lt (for lt), gt (for gt), lt (for lt),
    etc
  • Must adhere to XML 1.0 quoting rules
  • Can use logical operators
  • and
  • or

46
XSLT Stylesheets Transformations
  • What is XSLT?
  • The Basic Structure
  • Some Template Rules
  • More Advanced Structure
  • More Advanced Template Rules (or Features )
  • Transforming It All

47
What is XSLT?
  • Widely used and open standard defined by the W3C
  • A sub-specification of XSL
  • http//www.w3.org/TR/1999/REC-xslt-19991116
  • Designed to be used independently of XSL
  • Designed primarily for the transformation needed
    in XSL
  • W3C defines XSLT
  • a language for transforming XML documents
  • XSLT is more than a language its an XML
    programming language
  • Can have rules, evaluate conditions, etc
  • Offers the ability to transform one XML document
    into another
  • Transform an XDR Schema to and XSD Schema!
  • Transform an XML document into an HTML document

48
The XSLT Process Overview
Target Schema
XSLT Style Sheet
XML Source Document
XML Target Document
Source Schema
49
Transformation Process Overview
  • Pass source document to an XSLT processor
  • Processor contains a loaded XSLT style-sheet
  • Processor then
  • Loads the specified Stylesheet templates...
  • Traverses the source document, node by node...
  • Where a node matches a template...
  • Applies the template to the node
  • Outputs the (new) XML or HTML result document

50
Process of Transmutation
ltOrders gt ltOrderNogt 10 lt/OrderNogt ltProductNogt
100 lt/ProductNogt ltProductNogt 200
lt/ProductNogt lt/Orders gt ltOrders gt ltOrderNogt 20
lt/OrderNogt ltProductNogt 501 lt/ProductNogt lt/Orders
gt
ltHTMLgt ltBODYgt ltTABLE border 3gt
ltTRgt ltTDgt 10 lt/TDgt ltTDgt 100lt/TDgt
lt/TRgt ltTRgt ltTDgt 10 lt/TDgt
ltTDgt 200lt/TDgt lt/TRgt ltTRgt
ltTRgtlt/TRgt ltTDgt 20 lt/TDgt ltTDgt 501
lt/TDgt lt/TRgt lt/TABLEgt lt/BODYgt lt/HTMLgt
XSLT Processor
XSLT Stylesheet
51
Alchemy Anyone?
  • Need to declare the XSLT namespace
  • ltxslstylesheet xmlnsxsl"http//www.w3.org/1999/
    XSL/Transform"gt
  • xslstylesheet synonymous for xsltransform
  • Use patterns to locate nodes in the source
    document
  • Then transform the nodes as you like!

52
The Elements - Templates
  • ltxsltemplate/gt
  • Used for selecting node or node sub-tree
  • Use the match attribute to select a specific node
  • ltxsltemplate match ... gt
  • Then apply changes
  • ltxslapply-templates /gt
  • Used to recursively process children of the
    selected node
  • ltxslapply-templates select ... /gt
  • Used to select all nodes with a specific value

53
XSLT Alchemy By Example
lt?xml version'1.0'?gt ltxslstylesheet
xmlnsxsl"http//www.w3.org/TR/2000/CR-xsl-200011
21/"gt ltxsltemplate match"/"gt ltHTMLgt
ltBODYgt ltTABLE border 3gt
ltxslfor-each selectCustomer/Orders/OrderNo"gt
ltxslfor-each selectCustomer/Orders/Pro
ductNo"gt ltTRgt ltTDgt
ltxslvalue-of selectOrderNo"/gtlt/TDgt
ltTDgt ltxslvalue-of selectProductNo"/gtlt/TDgt
lt/TRgt lt/xslfor-eachgt
ltTRgtlt/TRgt lt/xslfor-eachgt
lt/TABLEgt lt/BODYgt lt/HTMLgt lt/xsltemplategt ltx
slstylesheetgt
54
Some More Elements
  • ltxslvalue-of select ... /gt
  • Select a node and insert its value into the
    output stream
  • Many, many more XSLT elements enabling
  • Repetition
  • lt xslfor-each select gt
  • Conditional processing
  • lt xslif test gt
  • lt xslchoose gt, ltxslwhen test gt,
    ltxslotherwisegt
  • Sorting
  • ltxslsort gt
  • Etc

55
Brief look at XML in .NET
  • .NET Support for XML
  • XML Namespaces in .NET
  • Some XML Classes in .NET

56
.NET Supports XML!
  • XML 1.0
  • http//www.w3.org/TR/1998/REC-xml-19980210
  • XML Namespaces
  • http//www.w3.org/TR/1999/REC-xml-names-19990114/
  • XML Schemas
  • http//www.w3.org/TR/2001/REC-xmlschema-1-20010502
    /
  • http//www.w3.org/TR/2001/REC-xmlschema-2-20010502
    /
  • XPath expressions
  • http//www.w3.org/TR/1999/REC-xpath-19991116
  • XSL/T transformations
  • http//www.w3.org/TR/1999/REC-xslt-19991116
  • DOM Level 1 and Level 2 Core
  • http//www.w3.org/TR/1998/REC-DOM-Level-1-19981001
    /
  • http//www.w3.org/TR/2000/REC-DOM-Level-2-Core-200
    01113/
  • SOAP 1.1
  • http//msdn.microsoft.com/xml/general/soapspec.asp

57
XML Namespaces in .NET
System.Xml
.Xsl
.XPath
.Schema
.Serialization
58
System.Xml Namespace
  • Overall namespace for classes that provide XML
    support
  • Classes for creating, editing, navigating XML
    documents
  • Reading, writing and manipulating documents via
    the DOM
  • Use the XmlDocument class for XML documents
  • Use the XmlDataDocument class relational or XML
    data
  • Classes that correspond to every type of XML
    element
  • XmlElement, XmlAttribute, XmlComment, etc
  • Used by the XmlDocument and XmlDataDocument
    classes

59
XmlReader
  • Abstract base class for reading XML
  • Fast, forward-only, non-cached XML stream reader
  • Base class for XmlTextReader
  • Properties of Interest
  • Value Gets the value of the node
  • NodeType Returns the type of node
  • HasValue Returns true if the node has a value
  • LocalName Gets the name of the node without its
    prefix
  • ReadState Returns the ReadState of the stream
  • Closed, EndOfFile, Error, Initial or Interactive

60
XmlWriter
  • Abstract base classes for writing XML
  • Fast, forward-only, non-cached XML stream writer
  • Base classes for XmlTextWriter
  • Properties of Interest
  • WriteState Returns the WriteState of the stream
  • Attribute, Content, Element, etc
  • XmlLang Returns the current xmllang scope
  • XmlSpace Returns the current xmlspace

61
XmlTextReader XmlTextWriter
  • Derived from the XmlReader XmlWriter abstract
    classes
  • Implement all the functionality defined by their
    base classes
  • Designed to work with a text based stream
  • As opposed to an in-memory DOM
  • Inherit the properties of the XmlReader and
    XmlWriter
  • XmlTextReader methods support reading XML
    elements
  • Read, MoveToElement, ReadString, etc
  • XmlTextWriter methods support writing XML
    elements
  • WriteDocType, WriteComment, WriteName, etc

62
XmlDocument
  • Derived from the XmlNode class
  • Represents an entire (in memory) XML document
  • Supports DOM Level 1 and Level 2 Core
    functionality
  • Reading writing built on top of XmlReader
    XmlWriter
  • Load a document and generate the DOM
  • Using URI, file, XmlReader, XmlTextReader or
    Stream

63
Properties Methods of Interest
  • Properties of Interest
  • ChildNodes Returns all the children of the
    current node
  • DocumentType Gets the DOCTYPE declaration node
  • DocumentElement Returns the root XmlElement
  • XmlResolver Used to resolve DTD schema
    references
  • FirstChild Returns the first child of the
    current node
  • ParentNode Returns the parent of the current
    node
  • Value Returns the (string) value of the current
    node
  • Methods of Interest
  • CreateComment Creates a comment node
  • CreateElement Creates an element node
  • Load Loads XML data using a URL, file, Stream,
    etc
  • Save Saves the XML document to a file, Stream,
    orwriter

64
XmlDocument the .NET DOM
System.Xml
.XPath
.Xsl
XmlCharType XmlComment XmlConvert XmlDataDocument
XmlDeclarationXmlDocumentXmlDocumentFragmentXml
DocumentTypeXmlElementXmlEntityXmlEntityReferen
ceXmlNamedNodeMap
XmlNodeXmlNodeReaderXmlNodeTypeXmlNotationXmlR
eaderXmlSpaceXmlText XmlTextReaderXmlTextWrite
rXmlUrlResolverXmlWhitespaceXmlWriter...
EntityHandling Formatting NameTable ReadState Tree
Position Validation WriteState XmlAttribute XmlAtt
ributeCollection XmlCDataSection XmlCharacterData
65
XmlDocument By Example
using System.Xml //Create an XmlDocument, Load
it, Write it to the Console //One
way XmlDocument xDoc new XmlDocument() xDoc.Lo
ad( C\\myData.xml") xDoc.Save( Console.Out)
//Second way (Use a XmlTextReader to read in load
the XML) XmlTextReader reader new
XmlTextReader(C\\myData.xml") xDoc.Load(
reader ) xDoc.Save( Console.Out) //Third way
(Use a XmlTextWriter to output the XML
document) XmlTextWriter writer new
XmlTextWriter( Console.Out ) writer.Formatting
Formatting.Indented xDoc.WriteContentTo( writer
) writer.Flush() Console.WriteLine()writer.Clo
se()
66
System.Xml.Xsl Namespace
  • Provides support for XSL Transformations
  • Some of the classes
  • XsltTransform Transforms using a stylesheet
  • XsltException Used to handle transformation
    exceptions
  • XsltContext The XSLT processors execution
    context

67
XsltTransform
  • Four simple steps to perform a transformation
  • Instantiate a XsltTransform object
  • Load a stylesheet
  • Load the data
  • Transform!

68
Transformation By Example
Using System.Xml.Xsl // 1. Create a
XslTransform object XslTransform xslt new
XslTransform() // 2. Load an XSL
stylesheetxslt.Load("http//somewhere/favorite.xs
l") // 3 4. Load the XML data file
transform!xslt.Transform(http//somewhere/mydata
.xml, C\\somewhere_else\\Transfo
rmedXmlOutput.xml )
69
Summary
  • XML is powerful, flexible, open extensible
  • XML is easy to learn easy to read easy to use
  • XML, XML Schema and XSLT combine to let you
  • Have data with semantics
  • Dictate and enforce you data structure
  • Separate data and data representation
  • Easily transform your data
  • .NET is XML-ized .NET lives on XML!
  • Not only exposes XML functionality, built using it

70
Section 4 QA
71
Document Object Model (DOM) 1/2
  • Use an XML parser to generate and manipulate the
    DOM
  • Load an XML file using a parser
  • Use the parsers programming interface to
  • Navigate through the Document Object Model
  • Manipulate the DOM Add, Delete, Move, Modify DOM
    elements
  • Using a DOM the parser can insure well formed
    documents
  • Some parsers can validate the DOM Validating
    Parser
  • By loading and comparing to either a DTD or a
    Schema

72
Document Object Model (DOM) 2/2
  • System.Xml contains DOM related classes
  • XmlDocument
  • XmlDataDocument
  • XmlNavigator
  • XmlDataNavigator
  • etc
  • .NET supports DOM Level 1 and most of the Level 2
    Core
  • http//www.w3.org/TR/1998/REC-DOM-Level-1-19981001
    /
  • http//www.w3.org/TR/2000/REC-DOM-Level-2-Core-200
    01113/

73
XML Namespaces 1/2
  • Another W3C specification
  • http//www.w3.org/TR/REC-xml-names/
  • Create collection of tags that share the same
    semantics
  • Used to qualify tags that would otherwise collide
  • Multiple documents can use the same tag
    differently
  • For example
  • Document A may use ltname/gt to designate a
    persons name
  • Document B may use ltname/gt to designate a file
    name

74
XML Namespaces 2/2
  • A URI is used to uniquely identify a namespace
  • xmlnsurnschemas-microsoft-comcustomerdata
  • May assign a namespace prefix to the namespace
  • xmlnsmsurnschemas-microsoft-comdata
  • Use the prefix to differentiate elements
    attributes
  • ltmsnamegt John Smith lt/msnamegt
  • Documents have a default namespace
  • Default prefix is xmlns
Write a Comment
User Comments (0)
About PowerShow.com