Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "XML C#.NET Software Development. eXtensible Markup Language Markup language that describes data Markup language that describes data Stores data as text."— Presentation transcript:

1 XML C#.NET Software Development

2 eXtensible Markup Language Markup language that describes data Markup language that describes data Stores data as text Stores data as text Easy to read/write Easy to read/write Very inefficient storage Very inefficient storage Has tags which encapsulate data and data structure Has tags which encapsulate data and data structure Has attributes which describe data Has attributes which describe data Does NOT describe data layout (Use XSLT) Does NOT describe data layout (Use XSLT)

3 XML Makeup Tags Tags Elements Elements Attributes Attributes Entities Entities Data Data Comments Comments

4 XML Tags Look the same as HTML tags Look the same as HTML tags Starting Tag: Starting Tag: Ending Tag: Ending Tag: Self-closing Tag: Self-closing Tag: Each tag must either: Each tag must either: Have a corresponding closing tag Have a corresponding closing tag Be self-closing Be self-closing Tags wrap data to create elements Tags wrap data to create elements

5 XML Elements Elements can be simple or complex Elements can be simple or complex The Title element is simple The Title element is simple The Book element is complex The Book element is complex The Outsiders S. E. Hinton Fox In Sox Dr. Suess

6 XML Attributes Stores data about the element (meta data) Stores data about the element (meta data) Attributes appear inside the element tag Attributes appear inside the element tag Attributes are made up of the attribute name, an equal sign, a value in quotes Attributes are made up of the attribute name, an equal sign, a value in quotes

7 XML Entities Like escape character sequences: Like escape character sequences: What if you want ‘>’ or ‘ ’ or ‘<‘ in your XML data? Entity Reference Character << >> && "“ &apos;‘

8 Entity Example x < y The Data here actually means: x < y

9 XML Data PCData PCData Will be parsed Will be parsed CData CData Will not be parsed Will not be parsed Mazda 626 1992 170,000

10 XML Comments Comments span multiple lines Comments span multiple lines Same as HTML Same as HTML <!-- starts a comment <!-- starts a comment --> ends a comment --> ends a comment

11 Well-Formed XML XML must be well-formed XML must be well-formed A document starts with the XML declaration A document starts with the XML declaration Each tag must have a closing tag Each tag must have a closing tag Tags can be self closing Tags can be self closing Tag boundaries must form a tree Tag boundaries must form a tree No overlapping tags No overlapping tags Must have exactly one unique root Must have exactly one unique root Tags are case sensative Tags are case sensative Attribute values must be in quotes Attribute values must be in quotes

12 XML Namespaces Used to avoid name collision Used to avoid name collision Can have default namespace and qualified namespace Can have default namespace and qualified namespace <human:member xmlns=“http://www.mywebsite.com” xmlns:human=“http://uri.mywebsite.com”> Sheldon 030473

13 XML Scenarios Application Persistent Xml File Save Settings Persistent Xml File Simple Database Persistent Xml File Configuration Information Xml Stream Xml Web Services Xml Stream Remote System Cross-process Communication Database Xml Stream Intermediate Storage Format

14 XML Object Serialization Save the state of your objects Save the state of your objects Use the XmlSerializer class Use the XmlSerializer class Serializes the public fields and properties Serializes the public fields and properties Properties must have get and set Properties must have get and set Requires a public default constructor Requires a public default constructor Serialize: store the information in XML Serialize: store the information in XML Deserialize: retrieve the information from XML Deserialize: retrieve the information from XML (See XMLSerialization Demo)

15 Collections and XML Collections are not “strongly typed” Collections are not “strongly typed” object typed object typed You can identify the underlying type(s) You can identify the underlying type(s) Each type in the collection can be tagged Each type in the collection can be tagged Use the XmlArrayItemAttribute attribute Use the XmlArrayItemAttribute attribute Use the XmlIgnoreAttribute to ignore public members that you don’t want serialized Use the XmlIgnoreAttribute to ignore public members that you don’t want serialized

16 Memento Design Pattern Preserves encapsulation of your object while representing its state Preserves encapsulation of your object while representing its state Object instance Memento (See MementoDemo)

17 Representing other types XML serialization only supports “primitive” types XML serialization only supports “primitive” types So how do we serialize other types? So how do we serialize other types? Font Font Color Color JPG JPG Have to convert all fields to “understood” types Have to convert all fields to “understood” types string string int int char char (See XmlFont)

18 The DOM The Document Object Model (The DOM) describes The Document Object Model (The DOM) describes how an XML document should be stored in memory how an XML document should be stored in memory What behaviors and methods should be available on it What behaviors and methods should be available on it http://www.w3.org/DOM/ http://www.w3.org/DOM/

19 XmlDocument Represents the DOM in memory Represents the DOM in memory Used to read and navigate XML Used to read and navigate XML Used to create XML Used to create XML (See XmlDocument)

20 XmlNode The document is a tree built of XmlNodes The document is a tree built of XmlNodes Properties: Properties: Attributes Attributes BaseURI BaseURI ChildNodes ChildNodes FirstNode FirstNode InnerText InnerText InnerXml InnerXml LastChild LastChild NextSibling NextSibling Value Value

21 XmlDocument Members: Methods Methods GetElementsById GetElementsById GetElementsByTagName GetElementsByTagName InsertAfter InsertAfter InsertBefore InsertBefore RemoveChild RemoveChild ReplaceChild ReplaceChild CreateNode CreateNode CreateElement CreateElement

22 .NET DOM Class Inheritance Object XmlNode XmlAttribute XmlDocument XmlDocumentFragment XmlEntity XmlLinkedNode XmlNotation XmlDataDocument XmlCharacterData XmlDeclaration XmlDocumentType XmlElement XmlEntityReference XmlProcessingInstruction XmlCDataSection XmlComment XmlSignificantWhiteSpace XmlText XmlWhitespace

23 XmlNode Composition Properties Attributes : XmlAttributeCollection BaseURI : string ChildNodes : XmlNodeList FirstChild : XmlNode HasChildNodes : bool InnerText : string InnerXml : string IsReadOnly : bool Item : XmlElement LastChild : XmlNode LocalName : string Name : string NamespaceURI : string NextSibling : XmlNode NodeType : XmlNodeType OuterXml : string OwnerDocument : XmlDocument ParentNode : XmlNode Prefix : string PreviousSibling : XmlNode Value : string Value depends on the NodeType Methods AppendChild Clone CloneNode (Can be a deep copy) CreateNavigator Equals GetEnumerator GetNamespaceOfPrefix GetPrefixOfNamespace InsertAfter InsertBefore Normalize PrependChild RemoveAll RemoveChild ReplaceChild SelectNodes (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)

24 XmlNodeType Enum: Enum: Attribute Attribute CData CData Comment Comment Document Document DocumentFragment DocumentFragment DocumentType DocumentType Element Element EndElement EndElement EndEntity EndEntity Entity Entity EntityReference EntityReference None None Notation Notation ProcessingInstruction ProcessingInstruction SignificantWhiteSpace SignificantWhiteSpace Text Text Whitespace Whitespace XmlDeclaration XmlDeclaration

25 XmlDocument Properties DocumentElement : XmlElement DocumentType : XmlDocumentType Implementation : XmlImplementation NameTable : XmlNameTable PreserveWhitespace : bool XmlResolver : XmlResolver (resolves dependencies) Methods CreateAttribute CreateCDataSection CreateComment CreateDocumentFragment CreateDocumentType CreateElement CreateEntityReference CreateNode CreateProcessingInstruction CreateSignificantWhitespace CreateTextNode CreateWhitespace CreateXmlDeclaration GetElementById GetElementsByTagName ImportNode Load LoadXml Save

26 XmlElement Properties HasAttributes : bool IsEmpty : bool Methods GetAttribute GetAttributeNode GetElementsByTagName HasAttribute RemoveAllAttributes RemoveAttribute RemoveAttributeAt RemoveAttributeNode SetAttribute SetAttributeNode

27 XmlReader Abstract base class Abstract base class Accesses: Accesses: Forward-only Forward-only Read-only Read-only Throws an XmlException if the XML is not well-formed Throws an XmlException if the XML is not well-formed Concrete Classes: Concrete Classes: XmlTextReader XmlTextReader Non-cached support, reads a byte stream Non-cached support, reads a byte stream XmlNodeReader XmlNodeReader Reads an XmlNode Reads an XmlNode XmlValidatingReader XmlValidatingReader Validates the XML as it reads Validates the XML as it reads

28 XmlWriter Abstract base class Abstract base class Accesses: Accesses: Forward-only Forward-only Write-only Write-only Concrete Classes: Concrete Classes: XmlTextReader XmlTextReader Non-cached support, reads a byte stream Non-cached support, reads a byte stream (See XmlDocument)

29 Validation Defines the legal building blocks of an XML document Defines the legal building blocks of an XML document Defines the document structure with a list of legal elements Defines the document structure with a list of legal elements Why Use Validation? Why Use Validation? Each of your XML files can carry a description of its own format Each of your XML files can carry a description of its own format Independent groups of people can agree to use a common DTD for interchanging data Independent groups of people can agree to use a common DTD for interchanging data Verify that the data you receive from the outside world is valid Verify that the data you receive from the outside world is valid verify your own data. verify your own data.

30 DTD: Old-Style DTD (Document Type Definition) is the old-style way of validation DTD (Document Type Definition) is the old-style way of validation A DTD can be declared inline in your XML document, or as an external reference A DTD can be declared inline in your XML document, or as an external reference

31 Declaring DTD Elements Element declarations: Element declarations: The element belongs to a category The element belongs to a category The element is only allowed the specified content The element is only allowed the specified content The element is allowed no content The element is allowed no content The element is allowed only character data The element is allowed only character data The element is unrestricted The element is unrestricted

32 DTD Structural Control must contain,, and must contain,, and In that order In that order Exactly once Exactly once Child must appear exactly once Child must appear exactly once Child must appear one or more times Child must appear one or more times Child must appear zero or more times Child must appear zero or more times Child must appear zero or one time Child must appear zero or one time Either one or two must appear once Either one or two must appear once

33 In-File DTD If the DTD is included in your XML source file, it should be wrapped in a DOCTYPE definition with the following syntax: If the DTD is included in your XML source file, it should be wrapped in a DOCTYPE definition with the following syntax: Example: Example: <!DOCTYPE note [ ]> Sarah Sheldon Reminder Buy me a birthday present!

34 Separate DTD File Precede the xml with: Precede the xml with:

35 DTD Attribute Declaration example: example: XML: XML:

36 Restricting Attributes attribute-type: attribute-type: default-value: default-value: ValueExplanation CDATA Character Data (value1|value2…) Value must be from the enumerated list ID Value must be a unique ID IDREF Value is a foreign ID ValueExplanationvalue The default value #REQUIRED The user must supply the value #IMPLIED The attribute is not required #FIXED value The value is fixed as specified

37 Define Your Own Entities Example: Example: DTD: DTD: XML: &dck; XML: &dck;

38 DTD Example <!DOCTYPE NEWSPAPER [ ]>

39 DTD Validation Use the XmlValidatingReader Use the XmlValidatingReader (See DTDValidation Demo)

40 Xml Schema Definition (XSD) Alternative to DTD Alternative to DTD More Powerful More Powerful More Complex More Complex Newer Newer Supports Datatypes Supports Datatypes Describe allowable values Describe allowable values Validation support for data Validation support for data Direct correlation with database Direct correlation with database Restrict data ranges Restrict data ranges A Schema is XML A Schema is XML

41 XSD: Reference To include an XSD (schema) file in your XML document put a reference to it in the root node as follows: To include an XSD (schema) file in your XML document put a reference to it in the root node as follows: <note xmlns="http://www.w3schools.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.w3schools.com note.xsd"> Sarah Sheldon Reminder Don't forget… something

42 Building an XSD Document Starts with a normal XML document tag: Starts with a normal XML document tag: The element is the root element of any xsd The element is the root element of any xsd Often the xs namespace is used: Often the xs namespace is used:...

43 XSD: Defining Simple Elements Simple elements can only contain text Simple elements can only contain text They cannot contain other elements They cannot contain other elements They cannot contain attributes They 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: Refsnes 34 1968-03-27

44 XSD: Default and Fixed Values Simple Elements allow for default and fixed values Simple Elements allow for default and fixed values XSD is as follows: XSD is as follows:

45 XSD: Facets (Restrictions) Facets are used to control the acceptable value domain for XML elements or attributes Facets are used to control the acceptable value domain for XML elements or attributes This defines a restriction on the simple element This defines a restriction on the simple element Its value must be an integer between 0 and 100 inclusively Its value must be an integer between 0 and 100 inclusively

46 XSD: 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 values “Audi”, “Golf”, and “BMW” This XSD fragment restricts the XML element(s) to contain the values “Audi”, “Golf”, and “BMW”

47 XSD: Patterned String Facet Use a regular expression to restrict the values of string types Use a regular expression to restrict the values of string types This XSD fragment restricts the value of the element to exactly three capital letters. This XSD fragment restricts the value of the element to exactly three capital letters.

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

49 XSD: Defining Complex Elements A complex element is an XML element that contains other elements and/or attributes A complex element is an XML element that contains other elements and/or attributes Describes the following XML: Describes the following XML: John Smith

50 XSD: 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 element indicates that the nested elements must appear in the given order. Note that the element indicates that the nested elements must appear in the given order.

51 XSD: Extending a Complex Type You can extend a complex type like this: You can extend a complex type like this:

52 XSD: 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 follows: Attributes are optional by default, you can make them required as follows:

53 XSD: Complex Text Only A “text-only” complex type can have text and attributes, but no nested elements A “text-only” complex type can have text and attributes, but no nested elements The tag indicates text-only The tag indicates text-only must contain either an or an tag must contain either an or an tag Allows for the following XML Allows for the following XML 35

54 XSD: Complex Mixed Elements Mixed elements allow text and other elements Mixed elements allow text and other elements This allows for the following XML This allows for the following XML Dear Mr. John Smith. Your order 1032 will be shipped on 2001-07-13.

55 XSD: Defining Empty Elements An empty complex element can contain attributes; but it cannot have any content between the opening and closing tags. An empty complex element can contain attributes; but it cannot have any content between the opening and closing tags. This allows for the following XML: This allows for the following XML:

56 XSD: Indicators Indicators control how elements are used in a document Indicators control how elements are used in a document Order Indicators Order Indicators Occurrence Indicators Occurrence Indicators Group Indicators Group Indicators

57 XSD: Order Indicators Order Indicators: Order Indicators: Indicates that all the sub-elements must appear exactly once in any order Indicates that all the sub-elements must appear exactly once in any order Indicates that exactly one sub-element must appear Indicates that exactly one sub-element must appear Indicates that the children must appear in the order they are listed Indicates that the children must appear in the order they are listed

58 XSD: Occurrence Indicators maxOccurs maxOccurs Indicates the maximum number of times an element can occur Indicates the maximum number of times an element can occur Default is 1 Default is 1 minOccurs minOccurs Indicates the minimum number of times an element can occur Indicates the minimum number of times an element can occur Default is 1 Default is 1 <xs:element name="child_name" type="xs:string" maxOccurs="10" minOccurs="0"/>

59 XSD: Group Indicators Group indicators are used to define related sets of elements Group indicators are used to define related sets of elements Element Groups Element Groups Attribute Groups Attribute Groups

60 XSD: 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,, or tag The elements in the group must be defined inside an,, or tag Reference the group like this: Reference the group like this:

61 XSD: Attribute Groups Attribute groups are defined with the attributeGroup declaration Attribute groups are defined with the attributeGroup declaration You can access the attribute group as follows: You can access the attribute group as follows:

62 and and allows any XML that may not be in the schema allows any XML that may not be in the schema allows attributes that may not exist in the schema allows attributes that may not exist in the schema

63 XSD: Element Substitution Allows us to use alternate element names Allows us to use alternate element names Allows for either: Allows for either: or or John Smith

64 XSD: Datatypes DatatypeDescription string Contains characters including whitespace. normalizedString The normalizedString data type also contains characters without whitespace. date Stored as YYYY-MM-DD time Stored as hh:mm:ss.s dateTime Stored as YYYY-MM-DDThh:mm:ss.s decimal Positive or negative number with or without a decimal point. integer Positive or negative number without a decimal point. boolean Represented by true or false. binary Can store any binary data (must use escape sequences). Plus Many more!

65 XSD Validation Use the XmlValidatingReader Use the XmlValidatingReader Subscribe to the Subscribe to the (See XSDValidation Demo)

66 XPath Paths in an xml document Paths 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

67 XPath: Paths Empire Burlesque Bob Dylan 10.90 Hide your heart Bonnie Tyler 9.90 Greatest Hits Dolly Parton 9.90 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

68 XPath: Expressions XPath defines a library of standard functions for working with strings, numbers and Boolean expressions. XPath defines a library of standard functions for working with strings, numbers and Boolean expressions. The XPath expression below selects all the cd elements that have a price element with a value larger than 10.80: The XPath expression below selects all the cd elements that have a price element with a value larger than 10.80:/catalog/cd[price>10.80] The following XPath expression selects the first cd child element of the catalog element: The following XPath expression selects the first cd child element of the catalog element:/catalog/cd[1] The following XPath expression selects the last cd child element of the catalog element (Note: There is no function named first()): The following XPath expression selects the last cd child element of the catalog element (Note: There is no function named first()): /catalog/cd[last()] /catalog/cd[last()]

69 XSLT XML StyLe sheet Transformation XML StyLe sheet Transformation The root element that declares the document to be an XSL style sheet is or. The root element that declares the document to be an XSL style sheet is or. Note: and are completely synonymous and either can be used! Note: and are completely synonymous and either can be used!

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


Download ppt "XML C#.NET Software Development. eXtensible Markup Language Markup language that describes data Markup language that describes data Stores data as text."

Similar presentations


Ads by Google