Similar presentations:
Working with XML. Data in. Net
1. Working with XML Data in .Net
Reviewed by Nazar Ivchenko26/08/2016
www.softserve.ua
2. 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
www.softserve.ua
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
data
<?xml version="1.0" encoding="UTF-8"?>
<case>
<product>
<manufacturer>Sony</manufacturer>
<speed>16</speed>
<description>CD-RW disks</description>
</product>
<product>
<manufacturer>Verbatim</manufacturer>
<speed>52</speed>
<description>DVD+R disks</description>
</product>
</case>
www.softserve.ua
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"?>
<person>
<name>
<first_name>Alan</first_name>
<last_name>Turing</last_name>
</name>
<profession>computer scientist</profession>
<profession>mathematician</profession>
<profession>cryptographer</profession>
</person>
www.softserve.ua
5. What is XML?
• The same building blocks as HTML – Element, Attribute, and Values• An element consists of opening tag and closing tag
<animal>Lion</animal>
• <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
</person>
Element:
<book>
<title>Trisman Shandy</title>
</book>
Attribute:
<book title="Trisman Shandy"></book>
www.softserve.ua
6. What is XML?
• XML Names Element and other XML names may contain essentiallyany 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
www.softserve.ua
7. Schemas and validation
• For validation of XML Document it should contain a reference to aDocument 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.
www.softserve.ua
8. DTD Example
<!ELEMENT<!ELEMENT
<!ELEMENT
<!ELEMENT
<!ELEMENT
person
name
first_name
last_name
profession
(name, profession*)>
(first_name, last_name)>
(#PCDATA)>
? - Zero or one of the element is allowed.
(#PCDATA)>
(#PCDATA)>
* - Zero or more of the element is allowed.
+ - One or more of the element is required.
<person>
<name>
<first_name>Alan</first_name>
<last_name>Turing</last_name>
</name>
</person>
<person>
<profession>computer scientist</profession>
<profession>mathematician</profession>
<profession>cryptographer</profession>
<person>
</person>
<profession>computer scientist</profession>
<name>
<first_name>Alan</first_name>
<last_name>Turing</last_name>
</name>
www.softserve.ua
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*)>
]>
<person>
<name>
<first_name>Alan</first_name>
<last_name>Turing</last_name>
</name>
<profession>computer scientist</profession>
<profession>mathematician</profession>
<profession>cryptographer</profession>
</person>
www.softserve.ua
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 "http://www.softservecom.com/dtds/person.dtd">
• 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\\"
"http://www.animals.com/xml/person.dtd">
www.softserve.ua
11. DTD Example
• Attribute Declarations<!ATTLIST image source CDATA #REQUIRED
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.
<performances dates="08-21-2001 08-23-2001 08-27-2001">
Kat and the Kings
</performances>
www.softserve.ua
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.
<!ATTLIST movie source ENTITY #REQUIRED>
<movie source="X-Men-trailer"/>
• 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.
<!ATTLIST employee social_security_number ID
<!ATTLIST project project_id
ID
<!ATTLIST team_member person
IDREF
<!ATTLIST assignment project_id
IDREF
#REQUIRED>
#REQUIRED>
#REQUIRED>
#REQUIRED>
www.softserve.ua
13. XSD
• XSD (XML Schema Definition) opened standard from W3C.<?xml version="1.0"?>
<books
schemalocation="file:///c:/data/books.xsd">
<book>
<title>Beginning Visual C#</title>
<author>Karli Watson</author>
<code>7582</code>
</book>
<book>
<title>Professional C# 3th
Edition</title>
<author>Simon
Robinson</author>
<code>7043</code>
</book>
</books>
<schema xmlns="http://www.w3.org/2001/XMLSchema">
<element name="books">
<complextype>
<choise maxOccurs="unbounded">
<!-- NO ORDER, COUNT >1 -->
<element name="book">
<complextype>
<sequence> <!-- ORDER -->
<element name="title" />
<element name="author" />
<element name="code" />
</sequence>
</complextype>
</element>
<choise>
<attribute name="schemalocation" />
</complextype>
</element>
<schema>
www.softserve.ua
14. Processing of XML-documents. XML-parser
• For working with XML XML-parser is used (software processing andvisualization).
• 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.
www.softserve.ua
15. Cascading Style Sheet (CSS)
• CSS-formatting is applied to the HTML(XML)-document, by browser onthe 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.
<animal>
<name>lion</name>
<weight>350 pounds</weight>
<height>350 pounds</height>
</animal>
www.softserve.ua
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}
www.softserve.ua
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.
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}
www.softserve.ua
18. Cascading Style Sheet (CSS)
• Choosing 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
www.softserve.ua
19. How to read-write XML document in .Net?
• There are 3 techniques available in .Net to parse XMLdocument:
Using XmlReader
Using XLINQ
Using XmlSerializer
• Assume that we have XML file as response from some Web
Service:
<User IsMember="true">
<Name>John</Name>
<Age>24</Age>
</User>
www.softserve.ua
20. Using 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();
www.softserve.ua
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.
www.softserve.ua
22. Using 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())
{ }
}
www.softserve.ua
23. Using 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);
}
}
www.softserve.ua
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");
www.softserve.ua
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;
});
www.softserve.ua
26. Using XmlSerializer
• XML data can be deserialized into a complex CLR type, where themapping 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; }
}
www.softserve.ua
27. Using XmlSerializer
• Then XmlSerializer is used to deserialize the XML into an instanceof 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;
www.softserve.ua