XML C#.NET Software Development. eXtensible Markup Language Markup language that describes data...

70
XML XML C# .NET Software Development C# .NET Software Development

Transcript of XML C#.NET Software Development. eXtensible Markup Language Markup language that describes data...

XMLXML

C# .NET Software DevelopmentC# .NET Software Development

eeXXtensible tensible MMarkup arkup LLanguageanguage

Markup language that describes dataMarkup language that describes dataStores data as textStores data as text

Easy to read/writeEasy to read/writeVery inefficient storageVery inefficient storage

Has tags which encapsulate data and data Has tags which encapsulate data and data structurestructure

Has attributes which describe dataHas attributes which describe dataDoes NOT describe data layout (Use XSLT)Does NOT describe data layout (Use XSLT)

XML MakeupXML Makeup

TagsTagsElementsElementsAttributesAttributesEntitiesEntitiesDataDataCommentsComments

XML TagsXML Tags

Look the same as HTML tagsLook the same as HTML tags Starting Tag: <MyXmlElement>Starting Tag: <MyXmlElement> Ending Tag: </MyXmlElement>Ending Tag: </MyXmlElement> Self-closing Tag: <SomeData />Self-closing Tag: <SomeData />

Each tag must either:Each tag must either: Have a corresponding closing tagHave a corresponding closing tag Be self-closingBe self-closing

Tags wrap data to create elementsTags wrap data to create elements

XML ElementsXML Elements

Elements can be simple or complexElements can be simple or complexThe Title element is simpleThe Title element is simpleThe Book element is complexThe Book element is complex

<Books> <Book> <Title>The Outsiders</Title> <Author>S. E. Hinton</Author> </Book> <Book> <Title>Fox In Sox</Title> <Author>Dr. Suess</Author> </Book><Books>

XML AttributesXML Attributes

Stores data about the element (meta data)Stores data about the element (meta data)Attributes appear inside the element tagAttributes appear inside the element tagAttributes are made up of the attribute name, Attributes are made up of the attribute name,

an equal sign, a value in quotesan equal sign, a value in quotes

<?xml version="1.0" encoding="utf-8" ?><configuration> <appSettings> <add key="ConnectionString" value="Server=localhost;”/> </appSettings></configuration>

XML EntitiesXML Entities Like escape character sequences:Like escape character sequences:

What if you want ‘>’ or ‘<‘ in your XML data?What if you want ‘>’ or ‘<‘ in your XML data?

Entity ReferenceEntity Reference CharacterCharacter

&lt;&lt; <<

&gt;&gt; >>

&amp;&amp; &&

&quot;&quot; ““

&apos;&apos; ‘‘

Entity ExampleEntity Example

<MathExpressions> <Expression>x &lt; y</Expression></MathExpressions>

The Data here actually means:x < y

XML DataXML Data PCDataPCData

Will be parsedWill be parsed CDataCData

Will not be parsedWill not be parsed

<Vehicles> <Car> <Make>Mazda</Make> <Model>626</Model> <Year>1992</Year> <Miles>170,000</Miles> </Car></Vehicles>

XML CommentsXML Comments

Comments span multiple linesComments span multiple linesSame as HTMLSame as HTML<!-- starts a comment<!-- starts a comment --> ends a comment--> ends a comment

<!-- this is a sample xml comment -->

Well-Formed XMLWell-Formed XML

XML must be well-formedXML must be well-formed A document starts with the XML declarationA document starts with the XML declaration

<?xml version="1.0"?><?xml version="1.0"?>

Each tag must have a closing tagEach tag must have a closing tag Tags can be self closingTags can be self closing

Tag boundaries must form a treeTag boundaries must form a tree No overlapping tagsNo overlapping tags

Must have exactly one unique rootMust have exactly one unique root Tags are case sensativeTags are case sensative Attribute values must be in quotesAttribute values must be in quotes

XML NamespacesXML Namespaces Used to avoid name collisionUsed to avoid name collision Can have default namespace and qualified Can have default namespace and qualified

namespacenamespace

<human:member xmlns=“http://www.mywebsite.com” xmlns:human=“http://uri.mywebsite.com”> <human:name>Sheldon</human:name> <dob>030473</dob></human:member>

XML ScenariosXML Scenarios

ApplicationPersistentXml File

SaveSettings Persistent

Xml File

SimpleDatabase

PersistentXml File

ConfigurationInformation

Xml Stream

Xml WebServices

Xml Stream

Remote System

Cross-processCommunication

Database

Xml StreamIntermediateStorage Format

XML Object SerializationXML Object Serialization

Save the state of your objectsSave the state of your objectsUse the XmlSerializer classUse the XmlSerializer class

Serializes the public fields and propertiesSerializes the public fields and propertiesProperties must have get and setProperties must have get and set

Requires a public default constructorRequires a public default constructorSerialize: store the information in XMLSerialize: store the information in XMLDeserialize: retrieve the information from XMLDeserialize: retrieve the information from XML

(See XMLSerialization Demo)

Collections and XMLCollections and XML

Collections are not “strongly typed”Collections are not “strongly typed”object typedobject typed

You can identify the underlying type(s)You can identify the underlying type(s)Each type in the collection can be taggedEach type in the collection can be tagged

Use the Use the XmlArrayItemAttribute XmlArrayItemAttribute attributeattribute

Use the XmlIgnoreAttribute to ignore Use the XmlIgnoreAttribute to ignore public members that you don’t want public members that you don’t want serializedserialized

Memento Design PatternMemento Design Pattern

Preserves encapsulation of your object Preserves encapsulation of your object while representing its statewhile representing its state

Object instance

Memento

(See MementoDemo)

Representing other typesRepresenting other types

XML serialization only supports “primitive” typesXML serialization only supports “primitive” types So how do we serialize other types?So how do we serialize other types?

FontFont ColorColor JPGJPG

Have to convert all fields to “understood” typesHave to convert all fields to “understood” types stringstring intint charchar (See XmlFont)

The DOMThe DOM

The Document Object Model (The DOM) The Document Object Model (The DOM) describes describes how an XML document should be stored in how an XML document should be stored in

memorymemoryWhat behaviors and methods should be What behaviors and methods should be

available on itavailable on it

http://www.w3.org/DOM/http://www.w3.org/DOM/

XmlDocumentXmlDocument

Represents the DOM in memoryRepresents the DOM in memoryUsed to read and navigate XMLUsed to read and navigate XMLUsed to create XMLUsed to create XML

(See XmlDocument)(See XmlDocument)

XmlNodeXmlNode

The document is a tree built of XmlNodesThe document is a tree built of XmlNodes Properties:Properties:

AttributesAttributes BaseURIBaseURI ChildNodesChildNodes FirstNodeFirstNode InnerTextInnerText InnerXmlInnerXml LastChildLastChild NextSiblingNextSibling ValueValue

XmlDocument Members:XmlDocument Members:

MethodsMethodsGetElementsByIdGetElementsByIdGetElementsByTagNameGetElementsByTagName InsertAfterInsertAfter InsertBeforeInsertBeforeRemoveChildRemoveChildReplaceChildReplaceChildCreateNodeCreateNodeCreateElementCreateElement

.NET DOM Class Inheritance.NET DOM Class InheritanceObject

XmlNode

XmlAttribute

XmlDocument

XmlDocumentFragment

XmlEntity

XmlLinkedNode

XmlNotation

XmlDataDocument

XmlCharacterData

XmlDeclaration

XmlDocumentType

XmlElement

XmlEntityReference

XmlProcessingInstruction

XmlCDataSection

XmlComment

XmlSignificantWhiteSpace

XmlText

XmlWhitespace

XmlNode CompositionXmlNode CompositionPropertiesAttributes : XmlAttributeCollectionBaseURI : stringChildNodes : XmlNodeListFirstChild : XmlNodeHasChildNodes : boolInnerText : stringInnerXml : stringIsReadOnly : boolItem : XmlElementLastChild : XmlNodeLocalName : stringName : stringNamespaceURI : stringNextSibling : XmlNodeNodeType : XmlNodeTypeOuterXml : stringOwnerDocument : XmlDocumentParentNode : XmlNodePrefix : stringPreviousSibling : XmlNodeValue : string

•Value depends on the NodeType

MethodsAppendChildCloneCloneNode (Can be a deep copy)CreateNavigatorEqualsGetEnumeratorGetNamespaceOfPrefixGetPrefixOfNamespaceInsertAfterInsertBeforeNormalizePrependChildRemoveAllRemoveChildReplaceChildSelectNodes (Uses XPath Expression)SelectSingleNode (Uses XPath Expression)Supports (Test if the DOM supports a specific feature)ToString (Overridden)WriteContentTo (writes children to an XmlWriter)WriteTo (writes the current node to an XmlWriter)

XmlNodeTypeXmlNodeType Enum:Enum:

AttributeAttribute CDataCData CommentComment DocumentDocument DocumentFragmentDocumentFragment DocumentTypeDocumentType ElementElement EndElementEndElement EndEntityEndEntity EntityEntity EntityReferenceEntityReference NoneNone NotationNotation ProcessingInstructionProcessingInstruction SignificantWhiteSpaceSignificantWhiteSpace TextText WhitespaceWhitespace XmlDeclarationXmlDeclaration

XmlDocumentXmlDocumentPropertiesDocumentElement : XmlElementDocumentType : XmlDocumentTypeImplementation : XmlImplementationNameTable : XmlNameTablePreserveWhitespace : boolXmlResolver : XmlResolver (resolves dependencies)

MethodsCreateAttributeCreateCDataSectionCreateCommentCreateDocumentFragmentCreateDocumentTypeCreateElementCreateEntityReferenceCreateNodeCreateProcessingInstructionCreateSignificantWhitespaceCreateTextNodeCreateWhitespaceCreateXmlDeclarationGetElementByIdGetElementsByTagNameImportNodeLoadLoadXmlSave

XmlElementXmlElementPropertiesHasAttributes : boolIsEmpty : bool

MethodsGetAttributeGetAttributeNodeGetElementsByTagNameHasAttributeRemoveAllAttributesRemoveAttributeRemoveAttributeAtRemoveAttributeNodeSetAttributeSetAttributeNode

XmlReaderXmlReader Abstract base classAbstract base class Accesses:Accesses:

Forward-onlyForward-only Read-onlyRead-only

Throws an XmlException if the XML is not well-formedThrows an XmlException if the XML is not well-formed Concrete Classes:Concrete Classes:

XmlTextReaderXmlTextReader Non-cached support, reads a byte streamNon-cached support, reads a byte stream

XmlNodeReaderXmlNodeReader Reads an XmlNodeReads an XmlNode

XmlValidatingReaderXmlValidatingReader Validates the XML as it readsValidates the XML as it reads

XmlWriterXmlWriter Abstract base classAbstract base class Accesses:Accesses:

Forward-onlyForward-only Write-onlyWrite-only

Concrete Classes:Concrete Classes: XmlTextReaderXmlTextReader

Non-cached support, reads a byte streamNon-cached support, reads a byte stream

(See XmlDocument)(See XmlDocument)

ValidationValidation Defines the legal building blocks of an XML documentDefines the legal building blocks of an XML document Defines the document structure with a list of legal Defines the document structure with a list of legal

elementselements

Why Use Validation?Why Use Validation? Each of your XML files can carry a description of its own formatEach of your XML files can carry a description of its own format Independent groups of people can agree to use a common DTD Independent groups of people can agree to use a common DTD

for interchanging datafor interchanging data Verify that the data you receive from the outside world is validVerify that the data you receive from the outside world is valid verify your own data. verify your own data.

DTD: Old-StyleDTD: Old-Style

DTD (Document Type Definition) is the DTD (Document Type Definition) is the old-style way of validationold-style way of validation

A DTD can be declared inline in your XML A DTD can be declared inline in your XML document, or as an external referencedocument, or as an external reference

Declaring DTD ElementsDeclaring DTD Elements

Element declarations:Element declarations: <!ELEMENT element-name category><!ELEMENT element-name category>

The element belongs to a categoryThe element belongs to a category <!ELEMENT element-name (content)><!ELEMENT element-name (content)>

The element is only allowed the specified contentThe element is only allowed the specified content <!ELEMENT element-name EMPTY><!ELEMENT element-name EMPTY>

The element is allowed no contentThe element is allowed no content <!ELEMENT element-name (#PCDATA)><!ELEMENT element-name (#PCDATA)>

The element is allowed only character dataThe element is allowed only character data <!ELEMENT element-name ANY><!ELEMENT element-name ANY>

The element is unrestrictedThe element is unrestricted

DTD Structural ControlDTD Structural Control <!ELEMENT data (one, two, three)><!ELEMENT data (one, two, three)>

<data> must contain <one>, <two>, and <three><data> must contain <one>, <two>, and <three> In that orderIn that order Exactly onceExactly once

<!ELEMENT element-name (child-name)><!ELEMENT element-name (child-name)> Child must appear exactly onceChild must appear exactly once

<!ELEMENT element-name (child-name+)> <!ELEMENT element-name (child-name+)> Child must appear one or more timesChild must appear one or more times

<!ELEMENT element-name (child-name*)> <!ELEMENT element-name (child-name*)> Child must appear zero or more timesChild must appear zero or more times

<!ELEMENT element-name (child-name?)> <!ELEMENT element-name (child-name?)> Child must appear zero or one timeChild must appear zero or one time

<!ELEMENT element-name (one|two)><!ELEMENT element-name (one|two)> Either one or two must appear onceEither one or two must appear once

In-File DTDIn-File DTD If the DTD is included in your XML source file, it should be wrapped If the DTD is included in your XML source file, it should be wrapped

in a DOCTYPE definition with the following syntax:in a DOCTYPE definition with the following syntax:

Example:Example:<!DOCTYPE root-element [element-declarations]>

<?xml version="1.0"?> <!DOCTYPE note [ <!ELEMENT note (to,from,heading,body)> <!ELEMENT to (#PCDATA)> <!ELEMENT from (#PCDATA)> <!ELEMENT heading (#PCDATA)> <!ELEMENT body (#PCDATA)> ]> <note> <to>Sarah</to> <from>Sheldon</from> <heading>Reminder</heading> <body>Buy me a birthday present!</body> </note>

Separate DTD FileSeparate DTD File

Precede the xml with:Precede the xml with: <!DOCTYPE root-element SYSTEM "filename"><!DOCTYPE root-element SYSTEM "filename">

DTD Attribute DeclarationDTD Attribute Declaration <!ATTLIST element-name attribute-name attribute-type default-<!ATTLIST element-name attribute-name attribute-type default-

value>value>

example: example:

<!ATTLIST payment type CDATA "check"> <!ATTLIST payment type CDATA "check">

XML: <payment type="check" /> XML: <payment type="check" />

Restricting AttributesRestricting Attributes

attribute-type:attribute-type:

default-value:default-value:

ValueValue ExplanationExplanation

CDATACDATA Character DataCharacter Data

(value1|value2…)(value1|value2…) Value must be from the enumerated listValue must be from the enumerated list

IDID Value must be a unique IDValue must be a unique ID

IDREFIDREF Value is a foreign IDValue is a foreign ID

ValueValue ExplanationExplanation

valuevalue The default valueThe default value

#REQUIRED#REQUIRED The user must supply the valueThe user must supply the value

#IMPLIED#IMPLIED The attribute is not requiredThe attribute is not required

#FIXED value#FIXED value The value is fixed as specifiedThe value is fixed as specified

Define Your Own EntitiesDefine Your Own Entities <!ENTITY entity-name “Entity-Value"> <!ENTITY entity-name “Entity-Value">

Example:Example: DTD: <!ENTITY dck "Donald Duck."> DTD: <!ENTITY dck "Donald Duck."> XML: <data>&dck;</data>XML: <data>&dck;</data>

DTD ExampleDTD Example<!DOCTYPE NEWSPAPER [ <!ELEMENT NEWSPAPER (ARTICLE+)> <!ELEMENT ARTICLE (HEADLINE,BYLINE,LEAD,BODY,NOTES)> <!ELEMENT HEADLINE (#PCDATA)> <!ELEMENT BYLINE (#PCDATA)> <!ELEMENT LEAD (#PCDATA)> <!ELEMENT BODY (#PCDATA)> <!ELEMENT NOTES (#PCDATA)> 

<!ATTLIST ARTICLE AUTHOR CDATA #REQUIRED> <!ATTLIST ARTICLE EDITOR CDATA #IMPLIED> <!ATTLIST ARTICLE DATE CDATA #IMPLIED> <!ATTLIST ARTICLE EDITION CDATA #IMPLIED>

<!ENTITY NEWSPAPER "Vervet Logic Times"> <!ENTITY PUBLISHER "Vervet Logic Press"> <!ENTITY COPYRIGHT "Copyright 1998 Vervet Logic Press"> ]>

DTD ValidationDTD Validation

Use the XmlValidatingReaderUse the XmlValidatingReader

(See DTDValidation Demo)

Xml Schema Definition (XSD)Xml Schema Definition (XSD)

Alternative to DTDAlternative to DTDMore PowerfulMore PowerfulMore ComplexMore ComplexNewerNewerSupports DatatypesSupports Datatypes

Describe allowable valuesDescribe allowable valuesValidation support for dataValidation support for dataDirect correlation with databaseDirect correlation with databaseRestrict data rangesRestrict data ranges

A Schema is XMLA Schema is XML

XSD: ReferenceXSD: Reference To include an XSD (schema) file in your XML document put a To include an XSD (schema) file in your XML document put a

reference to it in the root node as follows:reference to it in the root node as follows:

<?xml version="1.0"?><note xmlns="http://www.w3schools.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.w3schools.com note.xsd">

<to>Sarah</to> <from>Sheldon</from> <heading>Reminder</heading> <body>Don't forget… something</body> </note>

Building an XSD DocumentBuilding an XSD Document Starts with a normal XML document tag:Starts with a normal XML document tag:

<?xml version="1.0"?><?xml version="1.0"?> The <schema> element is the root element of any xsdThe <schema> element is the root element of any xsd

Often the xs namespace is used:Often the xs namespace is used:

<?xml version="1.0"?><xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" > ... ...</xs:schema>

XSD: Defining Simple ElementsXSD: Defining Simple Elements Simple elements can only contain textSimple elements can only contain text

They cannot contain other elementsThey cannot contain other elements They cannot contain attributesThey cannot contain attributes

In XSD we describe a simple element as follows:In XSD we describe a simple element as follows:

Allows the following XML:Allows the following XML:

<xs:element name="lastname" type="xs:string"/> <xs:element name="age" type="xs:integer"/> <xs:element name="dateborn" type="xs:date"/>

<lastname>Refsnes</lastname> <age>34</age> <dateborn>1968-03-27</dateborn>

XSD: Default and Fixed ValuesXSD: Default and Fixed Values Simple Elements allow for default and fixed valuesSimple Elements allow for default and fixed values

XSD is as follows:XSD is as follows:

<xs:element name="color" type="xs:string" default="red"/><xs:element name="color" type="xs:string" fixed="red"/>

XSD: Facets (Restrictions)XSD: Facets (Restrictions) Facets are used to control the acceptable value domain for XML Facets are used to control the acceptable value domain for XML

elements or attributeselements or attributes

This defines a restriction on the simple element This defines a restriction on the simple element <age><age> Its value must be an integer between 0 and 100 inclusivelyIts value must be an integer between 0 and 100 inclusively

<xs:element name="age"> <xs:simpleType> <xs:restriction base="xs:integer"> <xs:minInclusive value="0"/> <xs:maxInclusive value="100"/> </xs:restriction> </xs:simpleType></xs:element>

XSD: Enumeration FacetXSD: Enumeration Facet Restrict the element values to an enumerated list as follows:Restrict the element values to an enumerated list as follows:

This XSD fragment restricts the XML element(s) to contain the This XSD fragment restricts the XML element(s) to contain the values “Audi”, “Golf”, and “BMW”values “Audi”, “Golf”, and “BMW”

<xs:element name="car"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:enumeration value="Audi"/> <xs:enumeration value="Golf"/> <xs:enumeration value="BMW"/> </xs:restriction> </xs:simpleType></xs:element>

XSD: Patterned String FacetXSD: Patterned String Facet Use a regular expression to restrict the values of string typesUse a regular expression to restrict the values of string types

This XSD fragment restricts the value of the <initials> element to This XSD fragment restricts the value of the <initials> element to exactly three capital letters.exactly three capital letters.

<xs:element name="initials"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:pattern value="[A-Z][A-Z][A-Z]"/> </xs:restriction> </xs:simpleType></xs:element>

XSD: Defining a Facet DatatypeXSD: Defining a Facet Datatype You can define the facet as its own datatype so it can be reused by You can define the facet as its own datatype so it can be reused by

multiple elements:multiple elements:

<xs:element name="car" type="carType"/>

<xs:simpleType name="carType"> <xs:restriction base="xs:string"> <xs:enumeration value="Audi"/> <xs:enumeration value="Golf"/> <xs:enumeration value="BMW"/> </xs:restriction> </xs:simpleType>

XSD: Defining Complex ElementsXSD: Defining Complex Elements

A complex element is an XML element that contains other elements A complex element is an XML element that contains other elements and/or attributesand/or attributes

Describes the following XML:Describes the following XML:

<xs:element name="employee"> <xs:complexType> <xs:sequence> <xs:element name="firstname" type="xs:string"/> <xs:element name="lastname" type="xs:string"/> </xs:sequence> </xs:complexType> </xs:element>

<employee> <firstname>John</firstname> <lastname>Smith</lastname> </employee>

XSD: Defining a Complex TypeXSD: Defining a Complex Type Defining a complex type as its own type allow it to be reused:Defining a complex type as its own type allow it to be reused:

Note that the <xs:sequence> element indicates that the nested Note that the <xs:sequence> element indicates that the nested elements must appear in the given order.elements must appear in the given order.

<xs:element name="employee" type="personinfo"/><xs:element name="student" type="personinfo"/> <xs:element name="member" type="personinfo"/>

<xs:complexType name="personinfo"> <xs:sequence> <xs:element name="firstname" type="xs:string"/> <xs:element name="lastname" type="xs:string"/> </xs:sequence> </xs:complexType>

XSD: Extending a Complex TypeXSD: Extending a Complex Type

You can extend a complex type like this:You can extend a complex type like this:<xs:element name="employee" type="fullpersoninfo"/>

<xs:complexType name="personinfo"> <xs:sequence> <xs:element name="firstname" type="xs:string"/> <xs:element name="lastname" type="xs:string"/> </xs:sequence> </xs:complexType>

<xs:complexType name="fullpersoninfo"> <xs:complexContent> <xs:extension base="personinfo"> <xs:sequence> <xs:element name="address" type="xs:string"/> <xs:element name="city" type="xs:string"/> <xs:element name="country" type="xs:string"/> </xs:sequence> </xs:extension> </xs:complexContent> </xs:complexType>

XSD: Defining AttributesXSD: Defining Attributes Attributes must be inside a Complex Element definition:Attributes must be inside a Complex Element definition:

Attributes are optional by default, you can make them required as Attributes are optional by default, you can make them required as follows:follows:

<xs:element name=“LastName”> <xs:complexType> <xs:attribute name=“timezone” type=“xs:string” /> <xs:attribute name=“Lang” type=“xs:string” fixed=“EN” /> <xs:attribute name=“Loc” type=“xs:string” default=“US” /> <xs:complexType></xs:element>

<xs:attribute name="lang" type="xs:string" use="required"/>

XSD: Complex Text OnlyXSD: Complex Text Only A “text-only” complex type can have text and attributes, but no A “text-only” complex type can have text and attributes, but no

nested elementsnested elements The The <xs:simpleType><xs:simpleType> tag indicates text-only tag indicates text-only

<xs:simpleType><xs:simpleType> must contain either an must contain either an <xs:restriction><xs:restriction> or an or an <xs:extension><xs:extension> tag tag

Allows for the following XMLAllows for the following XML

<xs:element name="shoesize" type="shoetype"/>

<xs:complexType name="shoetype"> <xs:simpleContent> <xs:extension base="xs:integer"> <xs:attribute name="country" type="xs:string" /> </xs:extension> </xs:simpleContent> </xs:complexType>

<shoesize country="france">35</shoesize>

XSD: Complex Mixed ElementsXSD: Complex Mixed Elements Mixed elements allow text and other elementsMixed elements allow text and other elements

This allows for the following XMLThis allows for the following XML

<xs:element name="letter"> <xs:complexType mixed="true"> <xs:sequence> <xs:element name="name" type="xs:string"/> <xs:element name="orderid" type="xs:positiveInteger"/> <xs:element name="shipdate" type="xs:date"/> </xs:sequence> </xs:complexType> </xs:element>

<letter> Dear Mr.<name>John Smith</name>. Your order <orderid>1032</orderid> will be shipped on <shipdate>2001-07-13</shipdate>. </letter>

XSD: Defining Empty ElementsXSD: Defining Empty Elements An empty complex element can contain attributes; but it cannot An empty complex element can contain attributes; but it cannot

have any content between the opening and closing tags.have any content between the opening and closing tags.

This allows for the following XML:This allows for the following XML:

<xs:element name="product"> <xs:complexType> <xs:attribute name="prodid" type="xs:positiveInteger"/> </xs:complexType> </xs:element>

<product prodid="1345" />

XSD: IndicatorsXSD: Indicators Indicators control how elements are used in a documentIndicators control how elements are used in a document

Order IndicatorsOrder Indicators Occurrence IndicatorsOccurrence Indicators Group IndicatorsGroup Indicators

XSD: Order IndicatorsXSD: Order Indicators Order Indicators:Order Indicators:

<xs:all><xs:all> Indicates that all the sub-elements must appear exactly once in any orderIndicates that all the sub-elements must appear exactly once in any order

<xs:choice><xs:choice> Indicates that exactly one sub-element must appearIndicates that exactly one sub-element must appear

<xs:sequence><xs:sequence> Indicates that the children must appear in the order they are listedIndicates that the children must appear in the order they are listed

<xs:complexType name="personinfo"> <xs:sequence> <xs:element name="firstname" type="xs:string"/> <xs:element name="lastname" type="xs:string"/> </xs:sequence> </xs:complexType>

XSD: Occurrence IndicatorsXSD: Occurrence Indicators maxOccursmaxOccurs

Indicates the maximum number of times an element can occurIndicates the maximum number of times an element can occur Default is 1Default is 1

minOccursminOccurs Indicates the minimum number of times an element can occurIndicates the minimum number of times an element can occur Default is 1Default is 1

<xs:element name="person"> <xs:complexType> <xs:sequence> <xs:element name="full_name" type="xs:string"/> <xs:element name="child_name" type="xs:string" maxOccurs="10" minOccurs="0"/> </xs:sequence> </xs:complexType> </xs:element>

XSD: Group IndicatorsXSD: Group Indicators

Group indicators are used to define related Group indicators are used to define related sets of elements sets of elements Element GroupsElement Groups Attribute GroupsAttribute Groups

XSD: Element GroupsXSD: Element Groups Element groups are defined with the group declaration Element groups are defined with the group declaration

The elements in the group must be defined inside an <xs:all>, The elements in the group must be defined inside an <xs:all>, <xs:choice>, or <xs:sequence> tag<xs:choice>, or <xs:sequence> tag

Reference the group like this:Reference the group like this:

<xs:group name="persongroup"> <xs:sequence> <xs:element name="firstname" type="xs:string"/> <xs:element name="lastname" type="xs:string"/> <xs:element name="birthday" type="xs:date"/> </xs:sequence> </xs:group>

<xs:element name="person" type="personinfo"/>

<xs:complexType name="personinfo"> <xs:sequence> <xs:group ref="persongroup"/> <xs:element name="country" type="xs:string"/> </xs:sequence> </xs:complexType>

XSD: Attribute GroupsXSD: Attribute Groups Attribute groups are defined with the attributeGroup declarationAttribute groups are defined with the attributeGroup declaration

You can access the attribute group as follows: You can access the attribute group as follows:

<xs:attributeGroup name="personattrgroup"> <xs:attribute name="firstname" type="xs:string"/> <xs:attribute name="lastname" type="xs:string"/> <xs:attribute name="birthday" type="xs:date"/> </xs:attributeGroup>

<xs:element name="person"> <xs:complexType> <xs:attributeGroup ref="personattrgroup"/> </xs:complexType> </xs:element>

<xs:any> and <xs:anyAttribute><xs:any> and <xs:anyAttribute>

<xs:any> allows any XML that may not be <xs:any> allows any XML that may not be in the schemain the schema

<xs:anyAttribute> allows attributes that <xs:anyAttribute> allows attributes that may not exist in the schemamay not exist in the schema

XSD: Element SubstitutionXSD: Element Substitution Allows us to use alternate element namesAllows us to use alternate element names

Allows for either:Allows for either:

oror

<xs:element name="name" type="xs:string"/> <xs:element name="navn" substitutionGroup="name"/>

<xs:element name="customer" type="custinfo"/> <xs:element name="kunde" substitutionGroup="customer"/>

<xs:complexType name="custinfo"> <xs:sequence> <xs:element ref="name"/> </xs:sequence> </xs:complexType>

<customer> <name>John Smith</name> </customer>

<kunde> <navn>John Smith</navn> </kunde>

XSD: DatatypesXSD: Datatypes

DatatypeDatatype DescriptionDescription

stringstring Contains characters including whitespace. Contains characters including whitespace.

normalizedString normalizedString The normalizedString data type also contains characters without The normalizedString data type also contains characters without whitespace.whitespace.

datedate Stored as YYYY-MM-DDStored as YYYY-MM-DD

timetime Stored as hh:mm:ss.sStored as hh:mm:ss.s

dateTimedateTime Stored as YYYY-MM-DDThh:mm:ss.sStored as YYYY-MM-DDThh:mm:ss.s

decimaldecimal Positive or negative number with or without a decimal point.Positive or negative number with or without a decimal point.

integerinteger Positive or negative number without a decimal point.Positive or negative number without a decimal point.

booleanboolean Represented by true or false.Represented by true or false.

binarybinary Can store any binary data (must use escape sequences).Can store any binary data (must use escape sequences).

• Plus Many more!

XSD ValidationXSD Validation

Use the XmlValidatingReaderUse the XmlValidatingReaderSubscribe to the Subscribe to the

(See XSDValidation Demo)

XPathXPath

Paths in an xml documentPaths in an xml document syntax for defining parts of an XML document syntax for defining parts of an XML document uses paths to define XML elements uses paths to define XML elements defines a library of standard functions defines a library of standard functions a major element in XSLT a major element in XSLT not written in XML not written in XML a W3C Standard a W3C Standard

XPath: PathsXPath: Paths<?xml version="1.0" encoding="ISO-8859-1"?> <catalog> <cd country="USA"> <title>Empire Burlesque</title> <artist>Bob Dylan</artist> <price>10.90</price> </cd> <cd country="UK"> <title>Hide your heart</title> <artist>Bonnie Tyler</artist> <price>9.90</price> </cd> <cd country="USA"> <title>Greatest Hits</title> <artist>Dolly Parton</artist> <price>9.90</price> </cd> </catalog>

The XPath expression below selects the ROOT element catalog:

/catalog

The XPath expression below selects all the cd elements of the catalog element:

/catalog/cd

The XPath expression below selects all the price elements of all the cd elements of the catalog element:

/catalog/cd/price

XPath: ExpressionsXPath: Expressions XPath defines a library of standard functions for working with strings, numbers and XPath defines a library of standard functions for working with strings, numbers and

Boolean expressions. Boolean expressions.

The XPath expression below selects all the cd elements that have a price element The XPath expression below selects all the cd elements that have a price element with a value larger than 10.80:with a value larger than 10.80:

/catalog/cd[price>10.80]/catalog/cd[price>10.80]

The following XPath expression selects the first cd child element of the catalog The following XPath expression selects the first cd child element of the catalog element:element:

/catalog/cd[1]/catalog/cd[1]

The following XPath expression selects the last cd child element of the catalog The following XPath expression selects the last cd child element of the catalog element (Note: There is no function named first()):element (Note: There is no function named first()):

/catalog/cd[last()]/catalog/cd[last()]

XSLTXSLT

XXML ML SStytyLLe sheet e sheet TTransformationransformationThe root element that declares the The root element that declares the

document to be an XSL style sheet is document to be an XSL style sheet is <xsl:stylesheet> or <xsl:transform>.<xsl:stylesheet> or <xsl:transform>.Note:Note: <xsl:stylesheet> and <xsl:transform> <xsl:stylesheet> and <xsl:transform>

are completely synonymous and either can be are completely synonymous and either can be used!used!

Learn XMLLearn XML

For great tutorials and more complete For great tutorials and more complete information:information:http://www.w3schools.com/default.asphttp://www.w3schools.com/default.asp