Beruflich Dokumente
Kultur Dokumente
Agenda 1. Introduction 2. Rules for an XML DOC 3. Structure of XML Document 4. XML DOM Parser 5. XML and Dataset 6. XML DataDocument 7. XMLTextWriter & XMLTextReader 8. XPath Query 9. XPathDocument
XML Chapter-13
Table Of contents XM L XM L DOM P ARSER W ORKING WITH D ATASET XM LD ATA D OCUMENT XM LT EXT W RITER AND XM LT EXT R EADER XP ATH Q UERY XP ATH D OCUMENT 2 4 9 11 12 14 16
XML Chapter-13
XML
XML
is
a
universal
specification
/
standard
by
W3C
providing
context
/
description
and
structure
to
the
otherwise
ordinary
text
data.
XML
can
be
used
for
exchanging
information
between
objects
developed
in
different
programming
languages
and
running
on
discrete
platforms
and
even
if
the
objects
are
separated
by
the
firewall.
Fig 13.1 Rules for an XML DOC to be Well Formed It should have only one root element (tag) in XML document. Tags are case sensitive and hence the opening and closing tag case must match. Every tag must be closed. ex:<br></br> or <br/> Tags must not partially overlap each other. Ex: <b><i>Demo</b></i> is invalid The value of attributes must be enclosed in quotes (single or double) Ex: Roll No=104
An HTML document which is well formed is called XHTML An XMLSchema document contains declarations of various XML constructs including elements, attributes etc. These declarations define the syntax and the restrictions while using them in an instance document Note: Validation of an XML instance document is done by parser only if corresponding schema document is available i.e. Validation is optional.
XML Chapter-13
Student.xml <?xml version="1.0" encoding="UTF-8"?> <Students> <Student RollNo="101"> <Name>S1</Name> <Result>Passed</Result> </Student> <Student RollNo="104"> <Name>S4</Name> <Result>Failed</Result> </Student> <Student RollNo="105"> <Name>S5</Name> <Result>Passed</Result> </Student> </Students> Students.xml <Students> <Student RollNo="101"> <Name> <FirstName>AA</FirstName> <LastName>XX</LastName> </Name> <Result>Passed</Result> </Student> <Student RollNo="102"> <Name> <FirstName>BB</FirstName> <LastName>YY</LastName> </Name> <Result>Failed</Result> </Student> </Students>
Fig: 13.2
XML Chapter-13
XML Chapter-13
Fig 13.3 Example 1 XML continuation Dim doc As XmlDocument Dim enStuds As XmlElement Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyB ase.Load doc = New XmlDocument() 'doc.PreserveWhitespace = True doc.Load("..\..\Student.xml") enStuds = doc.DocumentElement
XML Chapter-13
For Each enStud As XmlElement In enStuds.ChildNodes cmbId.Items.Add(enStud.GetAttribute("RollNo")) Next End Sub Private Sub cmbId_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventA rgs) Handles cmbId.SelectedIndexChanged Dim enStud As XmlElement enStud = CType(enStuds.ChildNodes) txtName.Text = enStud.FirstChild.FirstChild.Value If (enStud.LastChild.FirstChild.Value = "Passed") Then rbnPassed.Checked = True Else rbnFailed.Checked = True End If End Sub Private Sub btnNames_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles b tnNames.Click Dim nlNames As XmlNodeList 'Collection of Nodes nlNames = doc.GetElementsByTagName("Name") Dim s As String = "" For Each enName As XmlNode In nlNames s = s + enName.FirstChild.Value + "\r\n" Next MessageBox.Show(s) End Sub Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn Add.Click Dim enStud, enName, enResult As XmlElement Dim tnName, tnResult As XmlText Dim anRollNo As XmlAttribute enStud = doc.CreateElement("Student") enName = doc.CreateElement("Name") enResult = doc.CreateElement("Result") tnName = doc.CreateTextNode(txtName.Text) If (rbnPassed.Checked) Then tnResult = doc.CreateTextNode("Passed") Else tnResult = doc.CreateTextNode("Failed") End If anRollNo = doc.CreateAttribute("RollNo") anRollNo.Value = cmbId.Text enStuds.AppendChild(enStud) enStud.AppendChild(enName) enStud.AppendChild(enResult) enName.AppendChild(tnName) enResult.AppendChild(tnResult) enStud.SetAttributeNode(anRollNo) doc.Save("..\..\Student.xml") cmbId.Items.Add(cmbId.Text) End Sub Private Sub btnRemove_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRemove.Click Dim enStud As XmlElement
XML Chapter-13
enStud = CType(enStuds.ChildNodes(cmbId.SelectedIndex), XmlElement) enStud.ParentNode.RemoveChild(enStud) doc.Save("..\..\Student.xml") cmbId.Items.Remove(cmbId.Text) End Sub Code: 13.2 VB Example 1 XML continuation XmlDocument doc; XmlElement studs; private void Form1_Load(object sender, EventArgs e) { doc = new XmlDocument(); doc.Load("Student.xml"); studs = doc.DocumentElement; //XmlElement enStud; foreach (XmlElement enStud in studs.ChildNodes) { cmbId.Items.Add(enStud.GetAttribute("RollNo")); } } private void cmbId_SelectedIndexChanged(object sender, EventArgs e) { XmlElement enStud; enStud = (XmlElement)studs.ChildNodes.Item(cmbId.SelectedIndex); txtName.Text = enStud.FirstChild.FirstChild.Value; if (enStud.LastChild.FirstChild.Value == "Passed") rbnPassed.Checked = true; else rbnFailed.Checked = true; } private void btnGetAllNames_Click(object sender, EventArgs e) { XmlNodeList n1; n1 = doc.GetElementsByTagName("Name"); string strNames = ""; foreach (XmlNode n in n1) strNames += n.FirstChild.Value + "\r\n"; MessageBox.Show(strNames); } private void btnAdd_Click(object sender, EventArgs e) { XmlElement enStud, enName, enResult; XmlText tnName, tnResult; XmlAttribute anId; enStud = doc.CreateElement("Student"); enName = doc.CreateElement("Name"); enResult = doc.CreateElement("Result"); tnName = doc.CreateTextNode(txtName.Text); if (rbnPassed.Checked) tnResult = doc.CreateTextNode("Passed"); else
XML Chapter-13
tnResult = doc.CreateTextNode("Failed"); anId = doc.CreateAttribute("RollNo"); anId.Value = cmbId.Text; studs.AppendChild(enStud); enStud.AppendChild(enName); enStud.AppendChild(enResult); enName.AppendChild(tnName); enResult.AppendChild(tnResult); enStud.SetAttributeNode(anId); doc.Save("Student.xml"); cmbId.Items.Add(cmbId.Text); MessageBox.Show("New Node Added with Id: " + cmbId.Text); } private void btnRemove_Click(object sender, EventArgs e) { XmlElement enStud; enStud = (XmlElement)studs.ChildNodes.Item(cmbId.SelectedIndex); enStud.ParentNode.RemoveChild(enStud); doc.Save("..\\..\\Student.xml"); cmbId.Items.Remove(cmbId.Text); MessageBox.Show("Node Removed"); } Code: 13.2 C#
XML Chapter-13
XML Chapter-13
Example 1 XML continuation private void btnSimpleDS_Click(object sender, EventArgs e) { DataSet ds = new DataSet(); ds.ReadXml("Student.xml"); DataRow dr; dr = ds.Tables["Student"].NewRow(); dr["RollNo"] = cmbId.Text; dr["Name"] = txtName.Text; if (rbnPassed.Checked) dr["Result"] = "Passed"; else dr["Result"] = "Failed"; ds.Tables["Student"].Rows.Add(dr); ds.WriteXml("Student.xml"); //cmbId.Items.Add(cmbId.Text); } private void btnDS_Click(object sender, EventArgs e) { DataSet ds = new DataSet(); ds.ReadXml("Students.xml"); //DataRow drStud; string s = ""; foreach (DataRow drStud in ds.Tables["Student"].Rows) { string name; DataRow[] drNames; drNames = drStud.GetChildRows("Student_Name"); //MessageBox.Show(drNames[0]["FirstName"].ToString ()); name = (string)drNames[0]["FirstName"] + "\t" + (string)drNames[0]["LastName"]; s += drStud["Student_Id"].ToString() + "\t" + drStud["RollNo"].ToString() + "\t" + name + "\t" + drStud["Result"].ToString() + "\r\n"; } MessageBox.Show(s); } Code: 13.3 C#
10
XML Chapter-13
XML DataDocument
XMLDataDocument
is
used
to
construct
an
XML
Dom
Tree
from
the
data
already
existing
in
Data
Set.
Its
a
class
Inherited
from
XMLDocument,
thus
this
has
all
the
properties
and
methods
which
the
XMLDocument
class
has.
Example
1
XML
continuation
Private
Sub
btnXmlDataDocument_Click(ByVal
sender
As
System.Object,
ByVal
e
As
System.EventArg s)
Handles
btnXmlDataDocument.Click
Dim
ds
As
New
DataSet()
ds.ReadXml("..\..\Students.xml")
Dim
dd
As
New
XmlDataDocument(ds)
MsgBox(dd.DocumentElement.OuterXml)
End
Sub
Code:
13.4
VB
Example
1
XML
continuation
private
void
btnXMLDataDocument_Click(object
sender,
EventArgs
e)
{
DataSet
ds
=
new
DataSet();
ds.ReadXml("Students.xml");
XmlDataDocument
dd
=
new
XmlDataDocument(ds);
MessageBox.Show(dd.DocumentElement.OuterXml);
}
Code:
13.4
C#
Fig. 13.4
11
XML Chapter-13
12
XML Chapter-13
Example 1 XML continuation private void btnXMLTextWriter_Click(object sender, EventArgs e) { XmlTextWriter xw = new XmlTextWriter("StudentNew.xml", System.Text.Encoding.UTF8); xw.Formatting = Formatting.Indented; xw.WriteStartDocument(); xw.WriteStartElement("Students"); xw.WriteStartElement("Student"); xw.WriteAttributeString("RollNo", "101"); xw.WriteElementString("Name", "S1"); xw.WriteElementString("Result", "Passed"); xw.WriteEndElement(); xw.WriteStartElement("Student"); xw.WriteAttributeString("RollNo", "102"); xw.WriteElementString("Name", "S2"); xw.WriteElementString("Result", "Failed"); xw.WriteEndElement(); xw.WriteEndElement(); xw.WriteEndDocument(); xw.Close(); } private void btnGetPassedStudents_Click(object sender, EventArgs e) { XmlTextReader xr = new XmlTextReader("../../Student.xml"); xr.WhitespaceHandling = WhitespaceHandling.None; string strNames = ""; string strCurrentName = ""; while (xr.Read()) { if (xr.NodeType == XmlNodeType.Element && xr.Name == "Name") { xr.Read(); strCurrentName = xr.Value; } else if (xr.NodeType == XmlNodeType.Element && xr.Name == "Result") { xr.Read(); if (xr.Value == "Passed") strNames += strCurrentName + "\n"; } } MessageBox.Show(strNames); } Code: 13.5 C#
13
XML Chapter-13
XPath
Query
XPath
is
a
specification
for
framing
of
Path
so
that
we
can
get
the
reference
to
nodes
in
XMLDocument
based
on
their
values.
Sample
XPaths:
E1/E2:
All
occurrences
of
E2
which
are
immediate
child
of
E1.
E1/*/E2:
All
occurrences
of
E2
which
are
grand
children
of
E1
E1//E2:
All
occurrences
of
E2
which
has
E1
as
ancestor.
//E1:
All
occurrences
of
E1
anywhere
in
the
document.
E1[1]:
First
occurrence
of
E1.
E1[last()]:
Last
occurrence
of
E1.
E1[E2]:
All
occurrence
of
E1
which
has
E2
as
child.
E1[E2
and
E3
]:
All
occurrence
of
E1
which
has
both
E2
and
E3
as
child.
E1[E2
or
E3
]:
All
occurrence
of
E1
which
has
either
E2
or
E3
as
child.
E1[not(E2)]:
All
occurrence
of
E1
where
E2
is
not
a
Child.
E1/@A1:
All
attributes
by
name
A1
for
every
occurrence
of
E1
element.
E1/@*:
All
attributes
of
all
occurrences
element
E1.
E1[@A1='1']:
All
occurrences
of
E1
where
attributes
A1=1.
E1/text():
Returns
all
the
text
nodes
under
E1.
E1/comment():
Returns
all
comment
nodes
under
E1
Arithmetic
Operators:
+,
-
,
*,
div
Logical
Operators:
and,
or,
not
Relation
Operators:
=,
!=,
<
,
>
<=,
>=
Example
1
XML
continuation
Private
Sub
btnGetListofStudentsUsingXPathQuery_Click(ByVal
sender
As
System.Object,
ByVal
e
As
System.EventArgs)
Handles
btnGetListofStudentsUsingXPathQuery.Click
Dim
doc
As
New
XmlDocument
doc.Load("../../Student.xml")
Dim
nl
As
XmlNodeList
nl
=
doc.SelectNodes(txtPath.Text)
Dim
str
As
String
=
""
For
Each
n
As
XmlNode
In
nl
str
&=
n.Name
&
"
-
"&
n.OuterXml
&
vbCrLf
Next
MsgBox(str)
End
Sub
Code:
13.6
VB
14
XML Chapter-13
Example 1 XML continuation private void btnGetListofStudentsUsingXPathQuery_Click(object sender, EventArgs e) { XmlNodeList nl = doc.SelectNodes(txtPath.Text); //txtPath = "//Student[Result/text() = 'Passed']/N ame/text()" string str = ""; foreach (XmlNode node in nl) { str += "Name: " + node.Name + " Value: " + node.OuterXml + "\n"; } MessageBox.Show(str); } Code: 13.6 C#
15
XML Chapter-13
XPathDocument
From
XPathDocument
we
get
an
XPathNavigator
and
using
this
we
compile
an
expression.
Using
XPathNavigator
and
XPathExpression
we
can
get
an
XPathNodeIterator
using
which
we
can
iterate
through
every
node
in
the
sort
order
as
specified
in
the
sort
expression
and
condition
as
specified
in
compiled
XPath
expression.
Example
1
XML
continuation
Private
Sub
btnXPathDocument_Click(ByVal
sender
As
System.Object,
ByVal
e
As
System.EventArgs)
Handles
btnXPathDocument.Click
Dim
doc
As
New
XPathDocument("Student.xml")
Dim
nav
As
XPathNavigator
=
doc.CreateNavigator()
Dim
expr
As
XPathExpression
=
nav.Compile("//Student")
expr.AddSort("@RollNo",
XmlSortOrder.Ascending,
XmlCaseOrder.LowerFirst,
"",
XmlDataType.Nu mber)
Dim
iterator
As
XPathNodeIterator
=
nav.Select(expr)
Dim
strNames
As
String
=
""
While
(iterator.MoveNext())
Dim
n
As
XPathNavigator
n
=
iterator.Current
n.MoveToChild(XPathNodeType.Element)
n.MoveToChild(XPathNodeType.Text)
strNames
&=
n.Value
+
"\r\n"
End
While
MessageBox.Show(strNames)
End
Sub
Code:
13.7
VB
Example
1
XML
continuation
private
void
btnXPathDocument_Click(object
sender,
EventArgs
e)
{
XPathDocument
doc
=
new
XPathDocument("Student.xml");
XPathNavigator
nav;
nav
=
doc.CreateNavigator();
XPathExpression
expr;
expr
=
nav.Compile("//Student");
expr.AddSort("@RollNo",
XmlSortOrder.Ascending,
XmlCaseOrder.LowerFirst,
"",
XmlDataType.Nu mber);
XPathNodeIterator
iterator;
iterator
=
nav.Select(expr);
string
strNames
=
"";
while
(iterator.MoveNext())
{
XPathNavigator
n;
n
=
iterator.Current;
n.MoveToChild(XPathNodeType.Element);
n.MoveToChild(XPathNodeType.Text);
strNames
+=
n.Value
+
"\r\n";
}
16
XML Chapter-13
Summary:
In
this
article,
we
have
studied
XML
DOM
structure
and
how
one
can
parse
XML
DOM
using
the
APIs
available
in
.net.
We
have
also
seen
working
with
dataset,
XML
Data
Document,
XML
Text
Reader
&
Writer
and
XPathQuery
along
with
XPathDocument.
17