Working with XML Data in .Net
What is XML?
What is XML?
What is XML?
What is XML?
Schemas and validation
DTD Example
DTD Example
DTD Example
DTD Example
DTD Example
Processing of XML-documents. XML-parser
Cascading Style Sheet (CSS)
Cascading Style Sheet (CSS)
Cascading Style Sheet (CSS)
Cascading Style Sheet (CSS)
How to read-write XML document in .Net?
Using XmlReader
Using XmlReader
Using XmlReader
Using XmlReader
Using XmlSerializer
Using XmlSerializer

Working with XML. Data in. Net

1. Working with XML Data in .Net

Reviewed by Nazar Ivchenko

2. Agenda

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

3. What is XML?

• XML – Extensible Markup Language
• Based upon HTML - describe your own tags
• Uses DTD ( Document Type Definition ) or Schemas to describe the
<?xml version="1.0" encoding="UTF-8"?>
<description>CD-RW disks</description>
<description>DVD+R disks</description>

4. What is XML?

• XML Trees. Parents and children. The root element
• Begin tag-end tag. Not cross-overlapped.
<?xml version="1.0" encoding="UTF-8"?>
<profession>computer scientist</profession>

5. What is XML?

• The same building blocks as HTML – Element, Attribute, and Values
• An element consists of opening tag and closing tag
• <animal class="mammals">Lion</animal> animal is the element,
class is the attribute and mammals is the value
• XML Attributes values ​are in single quotes (') or double quotes (").
<?xml version="1.0" encoding="UTF-8"?>
<person born="1912-06-23" died="1954-06-07">
Alan Turing
<title>Trisman Shandy</title>
<book title="Trisman Shandy"></book>

6. What is XML?

• XML 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: <!--This is the comment line-->
• CDATA section: <![CDATA[ and ]]>. Everything between the
<![CDATA[ and the ]]> is treated as raw character data.
<![CDATA[ <name>Lion</name> ]]>
be interpreted
The <name> element will not

7. Schemas 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.

8. DTD Example

(name, profession*)>
(first_name, last_name)>
? - Zero or one of the element is allowed.
* - Zero or more of the element is allowed.
+ - One or more of the element is required.
<profession>computer scientist</profession>
<profession>computer scientist</profession>

9. DTD Example

• Internal DTD Subsets
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE person [
<!ELEMENT first_name (#PCDATA)>
<!ELEMENT last_name (#PCDATA)>
<!ELEMENT profession (#PCDATA)>
<!ELEMENT name
(first_name, last_name)>
<!ELEMENT person (name, profession*)>
<profession>computer scientist</profession>

10. DTD Example

• Declaring a Personal External DTD. Refer to the DTD file (person.dtd)
that you have created by the URL.
• For external DTD subset, standalone=“no”.
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE person SYSTEM "">
• If your DTD will be used by others, you should name your DTD in a
standard way by a formal public identifier (FPI):
<?xml version="1.0" standalone="no"?>
<!DOCTYPE person PUBLIC "\\John Smith\\DTD Person\\EN\\"

11. DTD Example

• Attribute Declarations
• 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
<performances dates="08-21-2001 08-23-2001 08-27-2001">
Kat and the Kings

12. DTD Example

• Enumeration:
<!ATTLIST date month (January | February | March | April | May | June | July | August |
September | October | November | December) #REQUIRED>
• ENTITY attribute contains the name of an unparsed entity declared
elsewhere in the DTD.
<movie source="X-Men-trailer"/>
• ID attribute may contain an XML name that is unique within the XML
• IDREF type attribute refers to the ID type attribute of some element in
the document. Thus, it must be an XML name.
<!ATTLIST employee social_security_number ID
<!ATTLIST project project_id
<!ATTLIST team_member person
<!ATTLIST assignment project_id

13. XSD

• XSD (XML Schema Definition) opened standard from W3C.
<?xml version="1.0"?>
<title>Beginning Visual C#</title>
<author>Karli Watson</author>
<title>Professional C# 3th
<schema xmlns="">
<element name="books">
<choise maxOccurs="unbounded">
<!-- NO ORDER, COUNT >1 -->
<element name="book">
<sequence> <!-- ORDER -->
<element name="title" />
<element name="author" />
<element name="code" />
<attribute name="schemalocation" />

14. Processing of XML-documents. XML-parser

• For working with XML XML-parser is used (software processing and
• 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

15. Cascading 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
• The user controls the size, color, and spacing of this box.
<weight>350 pounds</weight>
<height>350 pounds</height>

16. Cascading Style Sheet (CSS)

• Inserting a Style Sheet to XML Document:
<?xml version=“1.0” ?>
<?xml-stylesheet type="text/css" href="animal.css" ?>
• 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}

17. Cascading Style Sheet (CSS)

• Positioning 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.
• Changing the Background.
name{display:block;color:magenta; background:url(background.jpg)}
name{display:block;color:magenta; background:color:magenta}

18. Cascading Style Sheet (CSS)

• Choosing a Font.
name{font-family:Georgia, Times}
• Italic and Bold Elements (can be bold, bolder, or lighter)
• Underline and Font Size.
• font size can also be absolute like small, medium, large

19. How to read-write XML document in .Net?

• There are 3 techniques available in .Net to parse XML
Using XmlReader
Using XmlSerializer
• Assume that we have XML file as response from some Web
<User IsMember="true">

20. Using XmlReader

XmlReader responseReader = XmlReader.Create(responseStream);
bool isMember = Boolean.Parse(responseReader.GetAttribute("IsMember"));
string name = responseReader.ReadContentAsString();
int age = responseReader.ReadContentAsInt();

21. Using XmlReader

XML 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.

22. Using XmlReader

using System;
using System.Xml;
using System.Xml.Schema;
class XmlSchemaSetExample
static void Main()
XmlReaderSettings booksSettings = new XmlReaderSettings();
booksSettings.Schemas.Add("", "books.xsd");
booksSettings.ValidationType = ValidationType.Schema;
booksSettings.ValidationEventHandler += new ValidationEventHandler(
XmlReader books = XmlReader.Create("books.xml", booksSettings);
while (books.Read())
{ }

23. Using XmlReader

static void booksSettingsValidationEventHandler(object sender,
ValidationEventArgs e)
if (e.Severity == XmlSeverityType.Warning)
Console.Write("WARNING: ");
if (e.Severity == XmlSeverityType.Error)
Console.Write("ERROR: ");

24. Using 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");

25. Using XLINQ

The 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.
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;

26. Using 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
public bool IsMember { get; set; }
public string Name { get; set; }
public int Age { get; set; }

27. Using XmlSerializer

• Then XmlSerializer is used to deserialize the XML into an instance
of the User class.
XmlSerializer serializer = new XmlSerializer(typeof(User));
User user = (User)serializer.Deserialize(responseStream);
bool isMember = user.IsMember;
string name = user.Name;
int age = user.Age;

English     Русский Правила