Working with XML. Data in. Net презентация

Agenda What is XML? Schema and validation DTD SXL Cascading Style Sheet (CSS) and XML How to read-write XML document in .Net? Using XMLReader Using Xlinq Using Serialization

Слайд 1Working with XML Data in .Net
Reviewed by Nazar Ivchenko
26/08/2016


Слайд 2Agenda

What is XML?
Schema and validation
DTD
SXL
Cascading Style Sheet (CSS) and XML
How to

read-write XML document in .Net?
Using XMLReader
Using Xlinq
Using Serialization






Слайд 3XML – Extensible Markup Language
Based upon HTML - describe your own

tags
Uses DTD ( Document Type Definition ) or Schemas to describe the data




Sony
16
CD-RW disks


Verbatim
52
DVD+R disks


What is XML?


Слайд 4XML Trees. Parents and children. The root element
Begin tag-end tag. Not

cross-overlapped.




Alan
Turing

computer scientist
mathematician
cryptographer

What is XML?


Слайд 5The same building blocks as HTML – Element, Attribute, and Values
An

element consists of opening tag and closing tag Lion
Lion animal is the element, class is the attribute and mammals is the value
XML Attributes values ​​are in single quotes (') or double quotes (").



Alan Turing


Element:

Trisman Shandy


Attribute:


What is XML?


Слайд 6XML Names Element and other XML names may contain essentially any

alphanumeric character (letters A - Z , a – z, 0 -9).
XML names may also include non-English letters, numbers, and ideograms such as ö.
XML names can’t contain other punctuation characters such as quotation marks(“), apostrophes(‘), dollar signs($), carets (^), percent symbols (%), and semicolons(;).
Comments are written like this:
CDATA section: . Everything between the is treated as raw character data.
Lion ]]> The element will not be interpreted

What is XML?


Слайд 7Schemas and validation
For validation of XML Document it should contain a

reference to a Document Type Definition (DTD) or XSD (XML Schema Definition), where its elements and attributes and grammatical rules for them are declared .
DTD or XML Schema includes:
Element and attribute names;
Relationships between elements and attributes and their structure;
Data types.

Слайд 8DTD Example

(first_name, last_name)>





Alan
Turing


? - Zero or one of the element is allowed.
* - Zero or more of the element is allowed.
+ - One or more of the element is required.


computer scientist
mathematician
cryptographer


computer scientist

Alan
Turing


Слайд 9Internal DTD Subsets





]>


Alan
Turing

computer scientist
mathematician
cryptographer

DTD Example


Слайд 10Declaring a Personal External DTD. Refer to the DTD file (person.dtd)

that you have created by the URL.
For external DTD subset, standalone=“no”.




If your DTD will be used by others, you should name your DTD in a standard way by a formal public identifier (FPI):

"http://www.animals.com/xml/person.dtd">


DTD Example


Слайд 11Attribute Declarations

width CDATA #REQUIRED
height CDATA #REQUIRED
alt CDATA #IMPLIED
>
CDATA attribute value can contain any string of text acceptable in a well-formed XML attribute value.
NMTOKEN: (name token) may consist of the same characters as an XML name, that is, alphanumeric and/or ideographic characters and the punctuation marks _, -, ., and :.
NMTOKENS contains one or more XML name tokens separated by whitespace.

Kat and the Kings

DTD Example


Слайд 12Enumeration:

May | June | July | August | September | October | November | December) #REQUIRED>
ENTITY attribute contains the name of an unparsed entity declared elsewhere in the DTD.


ID attribute may contain an XML name that is unique within the XML document.
IDREF type attribute refers to the ID type attribute of some element in the document. Thus, it must be an XML name.




DTD Example


Слайд 13XSD (XML Schema Definition) opened standard from W3C.

XSD



Beginning Visual C#
Karli Watson
7582


Professional C# 3th Edition
Simon Robinson
7043






















Слайд 14Processing of XML-documents. XML-parser
For working with XML XML-parser is used (software

processing and visualization).
There are two basic types of parsers:
Simple API for XML (SAX) and
Document Object Model (DOM).
SAX is based on the cursor and the events that occur when passing over the nodes of XML documents.
DOM loads the document completely in memory and presents it in a tree.

Слайд 15Cascading Style Sheet (CSS)
CSS-formatting is applied to the HTML(XML)-document, by browser

on the client side.
XML has no default formatting and needs information about how a tag will be displayed before being shown on a browser.
Every element that is styled with CSS can be thought of as an invisible box.
The user controls the size, color, and spacing of this box.



lion

350 pounds

350 pounds



Слайд 16Inserting a Style Sheet to XML Document:

?>

animal.css:
animal {display:block}
weight {display:block}
height {display:inline}
Block-level elements start at the beginning of a line
Inline elements appear within a line
Elements can be not displayed at all
height {display:none}

Cascading Style Sheet (CSS)


Слайд 17Positioning the Element
Relative - Moves the element with respect to the

original position.
description {display:block;position:relative;left:100px}
absolute -Moves the element with respect to the parent position.
description {display:block;position:absolute;left:100px}
Setting the Height or Width.
description {display:block;position:relative;left:100px; width:340px}
Changing the Foreground Color.
name{display:block;color:magenta}
Changing the Background.
name{display:block;color:magenta; background:url(background.jpg)}
name{display:block;color:magenta; background:color:magenta}

Cascading Style Sheet (CSS)


Слайд 18Choosing a Font.
name{font-family:Georgia, Times}
Italic and Bold Elements (can

be bold, bolder, or lighter)
name{font-style:italic}
Underline and Font Size.
name{text-decoration:underline}
name{font-size:10pt}
font size can also be absolute like small, medium, large

Cascading Style Sheet (CSS)


Слайд 19How to read-write XML document in .Net?
There are 3 techniques available

in .Net to parse XML document:
Using XmlReader
Using XLINQ
Using XmlSerializer
Assume that we have XML file as response from some Web Service:






John
24


Слайд 20Using XmlReader
XmlReader responseReader = XmlReader.Create(responseStream);

responseReader.Read();
bool isMember = Boolean.Parse(responseReader.GetAttribute("IsMember")); responseReader.Read();

responseReader.ReadStartElement("Name");
string name =

responseReader.ReadContentAsString();
responseReader.ReadEndElement();

responseReader.ReadStartElement("Age");
int age = responseReader.ReadContentAsInt();
responseReader.ReadEndElement();

responseReader.ReadEndElement();


Слайд 21XML documents are validated by the Create method of the XmlReader class.
To validate an

XML document, construct an XmlReaderSettings object that contains an XML schema definition language (XSD) schema with which to validate the XML document.
An individual schema or a set of schemas (as an XmlSchemaSet) can be added to an XmlSchemaSet by passing either one as a parameter to the Add method of XmlSchemaSet. 

Using XmlReader


Слайд 22Using XmlReader
using System;
using System.Xml;
using System.Xml.Schema;
class XmlSchemaSetExample
{

static void Main()
{
XmlReaderSettings booksSettings = new XmlReaderSettings();
booksSettings.Schemas.Add("http://www.contoso.com/books", "books.xsd");
booksSettings.ValidationType = ValidationType.Schema;
booksSettings.ValidationEventHandler += new ValidationEventHandler(
booksSettingsValidationEventHandler);
XmlReader books = XmlReader.Create("books.xml", booksSettings);
while (books.Read())
{ }
}


Слайд 23Using XmlReader
static void booksSettingsValidationEventHandler(object sender, ValidationEventArgs

e)
{
if (e.Severity == XmlSeverityType.Warning)
{
Console.Write("WARNING: ");
Console.WriteLine(e.Message);
}
else 
if (e.Severity == XmlSeverityType.Error)
{
Console.Write("ERROR: ");
Console.WriteLine(e.Message);
}
}

Слайд 24Using XLINQ

XmlReader responseReader = XmlReader.Create(responseStream);
XElement user = XElement.Load(responseReader);

bool isMember = (bool)user.Attribute("IsMember");
string

name = (string)user.Element("Name");
int age = (int)user.Element("Age");



Слайд 25The System.Xml.Schema namespace contains extension methods that make it easy to validate an

XML tree against an XML Schema Definition Language (XSD) file - Validate() methods
Validate() methods use an underlying XmlReader to validate the XML tree against an XSD.
Validation error and warning messages are handled using the ValidationEventHandler delegate. If no event handler is provided to these methods, validation errors are exposed as an XmlSchemaValidationException.

Using XLINQ

XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add("", "CustomersOrders.xsd");

XDocument custOrdDoc = XDocument.Load("CustomersOrders.xml");
bool errors = false;
custOrdDoc.Validate(schemas, (o, e) =>
{
Console.WriteLine("{0}", e.Message); errors = true;
});


Слайд 26Using XmlSerializer
XML data can be deserialized into a complex CLR type,

where the mapping from XML elements/attributes to object properties is controlled by the application developer.
The following CLR type is created and use the XmlElementAttribute and XmlAttributeAttribute to ensure that the names of elements and attributes match those in the XML.




public class User
{
[XmlAttribute]
public bool IsMember { get; set; }

[XmlElement]
public string Name { get; set; }

[XmlElement]
public int Age { get; set; }
}


Слайд 27Then XmlSerializer is used to deserialize the XML into an instance

of the User class.

Using XmlSerializer

XmlSerializer serializer = new XmlSerializer(typeof(User));
User user = (User)serializer.Deserialize(responseStream);

bool isMember = user.IsMember;
string name = user.Name;
int age = user.Age;


Обратная связь

Если не удалось найти и скачать презентацию, Вы можете заказать его на нашем сайте. Мы постараемся найти нужный Вам материал и отправим по электронной почте. Не стесняйтесь обращаться к нам, если у вас возникли вопросы или пожелания:

Email: Нажмите что бы посмотреть 

Что такое ThePresentation.ru?

Это сайт презентаций, докладов, проектов, шаблонов в формате PowerPoint. Мы помогаем школьникам, студентам, учителям, преподавателям хранить и обмениваться учебными материалами с другими пользователями.


Для правообладателей

Яндекс.Метрика