Professional Documents
Culture Documents
Chapter'12
;..,,1.,0ltt ·"'
UnitV
C:vrXML
r-~ I
Chapter Outline
12.1 Introduction: XML: Extensible Markup Language
12.2 XML Basics
12.3 The XML Classes
12.4 XML Validation
12.5 XML Display and Transforms
12.6 Questions
~,-
L::~ ~l J~~~!_!J:._~~J/t:_ )
= It is a very widely used format for exchanging data, mainly because it's easy readable for
both humans and machines.
= XML is designed as an all-purpose format for organizing data.
= A markup language is used to provide information about a document.
= Tags are added to the document to provide the extra information.
= HTML tags tell a browser how to display the document.
= XML tags give a reader some idea what some of the data means.
_;_- ~- >~~.t ,,r ,~ - . -. :/Sffl· .
---__,;::;...;;:....,;.;.£..,;:=~............-..;......._...:,.
When creating your own XML document, you need to remember only a few rules:
= XML documents must start with an XML declaration like <?xml version=" 1.0"?>.
= XML elements are composed of a start tag (like <Name>) and an end tag (like </Name>).
= Content is placed between the start and end tags. If you include a start tag, you must also
include a corresponding end tag.
= Whitespace between elements is ignored.
You can use only valid characters in the content for an element. You can't enter special
characters, such as the angle brackets (< >) and the ampersand (&), as content.
XML elements are case sensitive, so <ID> and <id> are completely different elements.
XML 317
Example
<?xml version="1.0" encoding="utf-S" ?>
<address>
<name>
<first>Haider</first>
<last>Zaidi</last>
</name>
<email>haiderzaidi20@gmail.com</email>
<phone>8898253962</phone>
<birthday>
<year>1988</year>
<month>04</month>
<day>03</day>
</birthday>
</address>
year /
day
"--
:> .NET provides a rich set of classes for XML manipulation in several namespaces that start
with System.Xml.
:> NET provides seven namespace:
using System.Xml;
using System.Xml.Scherna;
using System.Xml.Linq;
318 1n 9
using System.Xml.Resolvers;
,, using System.Xml.Serialization;
using System.Xml.XPath;
using System.Xml.Xsl;
The SystemXml namespace contains major XML classes. This namespace contai·ns tnan
classes to read and write XML documents. Y
using System;
using System.Text;
using System.Xml;
namespace ConsoleApplication3
{
class Program
lJl)IWriter.WriteStartElement: Writes out a start tag with the specified local name.
xmtWriter.WriteElementString: Writes an element containing a string value.
lllllWriter.WriteEndDocument: Closes any open elements or attributes and puts the writer
. the Start state.
back I0
lJl)IWriter.WriteAttributeString: This method writes out the attribute with a user defined
space prefix and associates it with the given namespace.
naJJle
12.3.2 XMLTextReader
:> With Xm!TextReader we parse XML data. This type acts upon a string containing XML
markup. We use the XmlTextReader constructor and develop a custom parser for XML data.
This is an efficient approach to XML parsing.
:> The Xm!Reader class is an abstract bases classes and contains methods and properties to
read a document. The Read method reads a node in the stream.
:> I'm using books.xml to read and display its data through XmlTextReader. This file comes
with VS.NET samples (https://msdn.microsoftcom/en-
us/Iibrary/ms762271(v=vs.85).aspx ).
Example
using System;
using System.Text;
using System.Xml;
namespace ConsoleApplication 1
class Program
•11un1111
--------=====------
ame:9enre ·
Base URI:file:///C:/books.xml
Local Name:genre
Attribute Count:0
i•(·
file:.///C:/USffl/N203TX/App0atall.ocal/Temporary ProJects/Consoli!Application 1/bin:'Debu~ConsoleAppliotion 1.EXE
Depth:2
Line Number:6
-
Node Type:EndElement
Attribute Count:
XmlTextReader. Properties Test
-------------------
Name:
Base URI:file:///C:/books.xml
ocal Name:
Attribute Count:0
Depth:2
Line Number:6
Node Type:Whitespace
Attribute Count:
322
~ c tDat~
.
Default.aspx code
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" lnherits="_Def;;
%>
<html xmlns="http://wWW.w3.org/1999/xhtml">
<head runat="server">
</head>
<body>
<form id="form1" rimat="server">
<div>
<table ciass="sty1e1 ">
<td class="sty1e3">
<asp:GridView ID="GridView1 • runat="server" BackColor="White" BorderColor="Whtte'
BorderWidth="2px" Ce11Padding="3" Gridlines="None" AutoGenerateColumns="False"
BorderStyle="Ridge" Height='281px" Width="538px"
onselectedindexchanged="GridView1 _SelectedlndexChanged" CellSpacing=' 1"
Font-Bold='True" Font-Names="Arial Black' Font-Size='X-Large'>
<FooterStyle BackColor="#C6C3C6" ForeColor="Black"></FooterStyle>
<HeaderStyle BackColor="#4A3CBC" Font-Bold='True" ForeColor="#E7E7FF"></HeaderStyle>
<PagerStyle HorizontalAlign="Right" BackColor="#C6C3C6" ForeColor="Black">
</PagerStyle>
<RowStyle BackColor="#DEDFDE" ForeColor="Black" />
ForeColor="White" Font•
<SelectedRowStyle BackColor-"#9471DE'
Bold="True"></SelectedRowStyle>
<Columns>
<asp:BoundField DataField="FirstName· HeaderText="First Name' ReadOnly="true· />
~L ill
oefault.aspx.cs code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Linq;
FirstName = r.Element("FirstName").Value,
Age= r.Element("Age").Value,
Dept= r.Element("Dept").Value
MiiMHMGAi+®ni41l
d
};
GridView1 .DataSource = query;
GridView1 .DataBind();
l
l
© ioc>"'°'t1S952JUNQ10XMI/DmUit.asp,
Select Data I
ZAIDI
ARIF
~ .-~fr,
-'-_.,,,...,;.~~
ilf11r;~.-,~~·",
-~- ; - - ~
XML bas a rich set of supporting standards, many of which are far beyond the scope of this book.
One of the most useful in this family of standards is XML Schema. XML Schema defmes the rules to
which a specific XML document should conform, such as the allowable elements and attributes, the
order of elements, and the data type of each element. You define these requirements in an XML
Schema document (XSD).
L t::__
XML 325
Example
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
lnherits="XmlValidalion" %>
<html xmlns="http://www.w3.org/1999/xhtm1" >
<head runat="server">
<title>Xml Validation</title>
</head>
<body>
<form id="form1 • runat="server">
<div class="Box">
<asp:RadioButton id="optValid"
runat="server"
Text="Use Data.xml"
Checked="True"
GroupName="Valid">
</asp:RadioButton>
<asp:button id="crndValidate"
runat="server''
Text="Validate XML"
OnClick="cmdValidate_Click">
</asp:button>
</div>
<div>
<asp:Label id="lblStatus" runat="server" EnableViewState="False"></asp:Label>
</div>
</form>
</body>
</html>
File: Default.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.LIi;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
32 ng
using System.Web.UI.HtmlControls;
using System.Xml.Schema;
using System.IC;
using System.Xml;
{
protected void crndVal'date_Click(object sender, EventArgs e)
{
string filePath = "Data.xml";
lblStatus.Text = "";
while (r.Read())
{
l
ls.Close();
File: Data.xml
<?xml version='1.0' encoding='utf-8' ?>
<EmployeeDetails>
<FirstName>ZAIDl</FirstName>
)(ML 327
.:MiddleName>ZARl</MiddleName>
<LastName>HAIDER~/LastName>
<Emai11d>haid~rzaidi20@gmail.com</Emailld>
.:Mobile>8898253962</Mobile>
-=:Address>B/503, Jogeshwari , Mumbai</Address>
<Blke>Yamaha FZS</Bike>
</EmployeeDetails>
File: Oata.xsd
Open the existing XML.
Go to XML menu.
·Select "Create schema"- option.
Your XSD will be created automatically.
<?xml version="1.0" encoding="utf-8"?>
<xs:schema. attributeFormDefault="unqualified" elementFormDefault="qualified"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="EmployeeDetails">
<xs:complexType>
<xs:sequence>
<xs:element name="FirstName" type="xs:string" />
<xs:element name="MiddleName" type="xs:string" />
<xs:element name="LastName" type="xs:string" />
<xs:element name="Emailld" type="xs:string" />
<xs:element name="Mobile" type="xs:unsignedLong"/>
<xs:element name="Address" type="xs:string" />
<xs:element name="Bike" type="xs:string" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
Example
XML File: XMLFiJe.xml
<?xml version='1.0" encoding='utf-8' ?>
<breakfast_meru>
<food>
<name>Biriyani</name>
<price>$10.60</price>
<description>Rice with chicken</description>
<calories>650</calories>
</food>
<food>
<name>Juice</name>
<price>$4.20</price>
<description>Frult juices like mango, banana, apple</description>
<calories>200</calories>
</food>
</breakfast menu>
XML 329
XSLTFile
XSLTFile.xslt
1 ....
'°:?xml version="1.0" encoding="iso-8859-1"?> ' t 11;,
<html xsl:version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns="http://www.w3.org/1999/xhtml">
<body style="font-family:Arial;font-size:12pt;background-color:#EEEEEE">
<xsl:for-each select="breakfast_menu/food"> r.
<div style="background-color:teal;color:white;padding:4px">
<span style="font-weight:bold">
<xsl:value-of select="name"/>
</span>
- <xsl:value-of select="price"/>
</div>
<div style="margin-left:20px;margin-bottom:1em;font-size:1 Opt">
<xsl :value-of select="description"/>
- ,e,•
<span style="font-style:italic">
<xsl:value-of select="calories"/> -(calories per serving)
</span>
</div>
</xsl:for-each>
</body>
</html>
<html xmlns="http:/Jwww.w3.org/1999/xhtml">
<head n1nat='server">
<ti11e></title>
</head>
<bOdy>
<form ld='form1' n1nat=·server">
<div>
</div>
</form>
</body>
</html>
)(ML
331
+
C' 1,) ©"'
Label
Webforml.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IQ;
using System.Xml;
using System.Xml.Schema;
using System.Xml.XPath;
using System.Xml.Xsl;
using System.Web.UI;
using System.Text;
using System.Web.UI.WebControls;
// This is being read from the same folder as this page is in.(only for demo purpose)
// In real applications this xml might be coming from some external source or database.
string xmlString = File.ReadAIIText(Server.MapPath("XMLFile.xml"));
}
protected void Button2_Click(object sender, EventArgs e)
{
Xml1.Visible = false;
Label1.Visible = true;
II Creating StringBuilder object to hold html data and creates TextWriter object to hold data f
XslCompiled.Transform method rom
StringBuilder htrnlOu1put = new StringBuilder();
TextWriter htrnlWriter = new StringWriter(htmlOutput);
II Call Transform() method to create html string and write in TextWriter object.
objXSLTransform.Transform(reader, null, htmlWriter);
Label1 .Text = htmlOutput.ToString();
,
XML
333
1oe.n,o,t:614Z/Wtblorm1/Weblorn X +
®
l~ <:! Q
~r.l""'.~;. - .m•,.,.-__ . .. .
¼ ~\,..,-i;:.· .
©
-_
IOCalnost:t, l '1
. '""'- ~
..,,. -
t;.... -....-- -.,. - - .,_,," _ ...
1
• ·• '" [!<ML Display I , [ Without_XML Control \
Biriyani - $10.60
Rice with chicken650 (calories per serving)
Juice - $4.20
Frurt juices like mango, banana, apple200 (calories per serving)
i1
loc,lloldlW#mforfflVWcllfo.-,· )(
I~.: C! 0 ~ - ll!l@ -
f. XMl.;J}i~play
Biriyani - $10.60
Rlct with _151),_ ,,.,-inw
Juice - $4.20
FrultjulCIO 11<,-. bo111111, oppllm/-por-'"11/