XML
July 17, 2017 | Author: Muskula Vineeth Reddy | Category: N/A
Short Description
Download XML...
Description
XML Chapter-13
Deccansoft Software Services 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
Table Of contents XM L
2
XM L DOM P ARSER
4
W ORKING WITH D ATASET
9
XM LD ATA D OCUMENT
11
XM LT EXT W RITER AND XM LT EXT R EADER
12
XP ATH Q UERY
14
XP ATH D OCUMENT
16
1
XML Chapter-13
Deccansoft Software Services
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: or
Ø
Tags must not partially overlap each other. Ex: Demo 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.
2
XML Chapter-13
Deccansoft Software Services Structure of XML Document (HAS A – Relationship)
Student.xml S1 Passed S4 Failed S5 Passed
Students.xml AA XX Passed BB YY Failed
Fig: 13.2
3
XML Chapter-13
Deccansoft Software Services
XML DOM Parser XML DOM (Document Object Model) Ø
It is a specification by W3C and implemented by vendors for different languages on their respective platform.
Ø
XML DOM is a collection of objects created using the various constructs in an xml document. These objects are arranged in memory in a tree like structure
Ø
Using DOM API we can read the data from xml document and we can also create an xml document from start or edit an already existing xml document.
Ø
XMLNode is the parent class of all XML classes representing various constructs in an XML document. Note: SAX Parser– Simple API for XML is event based parser but not supported by MS.NET and instead XMLTextReader is used.
Example 1 -‐ XML Private Sub btnShow_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bt nShow.Click Dim doc As New XmlDocument() doc.PreserveWhitespace = True doc.Load("../../student.xml") Dim enStudents As XmlElement enStudents = doc.DocumentElement Dim enStud As XmlElement = enStudents.ChildNodes(0) Dim anRollNo As XmlAttribute = enStud.Attributes("RollNo") MessageBox.Show(anRollNo.Value) MessageBox.Show(enStud.GetAttribute("RollNo")) Dim enName As XmlElement = enStud.FirstChild Dim tnName As XmlText = enName.FirstChild MessageBox.Show(tnName.OuterXml) End Sub Code: 13.1 VB Example 1 -‐ XML using System.Xml; private void btnShow_Click(object sender, EventArgs e) { XmlDocument doc = new XmlDocument(); //doc.PreserveWhitespace = true; //Creates a tree of objects from an XML file / document. doc.Load("../../student.xml"); XmlElement enStudents; //Returns the reference to Root node of an xml document. enStudents = doc.DocumentElement; //Returns the first Student reference
4
XML Chapter-13
Deccansoft Software Services XmlElement enStud = (XmlElement)enStudents.ChildNodes[0]; //Returns ref to attribute by name “RollNo” XmlAttribute anRollNo = enStud.Attributes["RollNo"]; MessageBox.Show(anRollNo.Value); //Shows the value of attribute “RollNo” MessageBox.Show(enStud.GetAttribute("RollNo")); XmlElement enName = (XmlElement)enStud.FirstChild; //Returns the ref to Text inside XmlText tnName = (XmlText)enName.FirstChild; MessageBox.Show(tnName.OuterXml); } Code: 13.1 C#
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
5
Deccansoft Software Services
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
6
Deccansoft Software Services
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
7
Deccansoft Software Services
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#
8
Deccansoft Software Services
XML Chapter-13
Working with Dataset Types of XML Elements: Complex Type: An element which has either attributes or child elements is a complex type of element. Simple Type: If it is not complex then it is a simple type of element. All attributes are always simple type. When the XML document is loaded into Dataset then every Complex Type is loaded Data Table and the simple types with in it are loaded as Data Columns. Also the root element name is used as dataset name. If one complex type is nested within the other complex type then a Data Relation object is created using those two Complex types / Data Tables. If they do not have any common field between them, then a column in the format of _Id is added to both the Data Tables. Ex:
Student (RollNo, Name, Student_Id) – Data Table Name (FirstName, LastName, Student_Id) – Data Table Student_Name – Data Relation
Example 1 – XML continuation Private Sub btnSimpleDS_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handle s btnSimpleDS.Click Dim ds As New DataSet() 'Dim strXML As String 'strXML = "< ….some xml content….> " 'ds.ReadXml(New StringReader(strXML)) //To read from a string with xml content ds.ReadXml("../../Student.xml") Dim dr As DataRow dr = ds.Tables("Student").NewRow dr("RollNo") = cmbId.Text dr("Name") = txtName.Text If (rbnPassed.Checked) Then dr("Result") = "Passed" Else dr("Result") = "Failed" End If ds.Tables("Student").Rows.Add(dr) ds.WriteXml("../../Student.xml") End Sub Private Sub btnDS_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnD S.Click Dim ds As New DataSet() ds.ReadXml("..\..\Students.xml") Dim drStud As DataRow Dim s As String = "" For Each drStud In ds.Tables("Student").Rows Dim name As String Dim drsName As DataRow() drsName = drStud.GetChildRows("Student_Name") name = CStr(drsName(0)("FirstName")) & vbTab & CStr(drsName(0)("LastName")) s &= CStr(drStud("RollNo")) & vbTab & name & vbTab & CStr(drStud("Result")) & vbCrLf Next
9
Deccansoft Software Services
XML Chapter-13
MessageBox.Show(s) End Sub Code: 13.3 VB 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
Deccansoft Software Services
XML DataDocument XMLDataDocument is used to construct an XML Dom Tree from the data already existing in Data Set. It’s 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
Deccansoft Software Services
XML Chapter-13
X MLTextWriter and XMLTextReader XMLTextReader and XMLTextWriter are stream based parsers and can be used for situation in
Ø
which an XML Document needs to be parsed only once. This way of parsing the document is very fast when compared to DOM API as the complete document doesn’t have to load into memory at once. This is also because XMLTextReader uses Linear Parsing i.e. Forward Only Parsing and the is only used for READONLY operations. Using XMLWriter we can create a new XML file but we cannot modify the already existing XML file.
Ø
Example 1 – XML continuation Private Sub btnXmlTextWriter_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) H andles btnXmlTextWriter.Click Dim tw As New XmlTextWriter("c:\demo.xml", Nothing) tw.WriteStartDocument() tw.WriteStartElement("Students") 'For Complex type of element tw.WriteStartElement("Student") tw.WriteAttributeString("RollNo", "101") 'Adds an attribute to the immediate element already writ ten tw.WriteElementString("Name", "S1") 'Write Simple type tw.WriteElementString("Result", "Passed") tw.WriteEndElement() 'Ends Student tag tw.WriteEndElement() 'Ends Students tag tw.WriteEndDocument() 'Closes the document tw.Flush() tw.Close() End Sub Private Sub btnTextReader_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Hand les btnTextReader.Click Dim xr As New XmlTextReader("../../Student.xml") xr.WhitespaceHandling = WhitespaceHandling.None Dim strPassedNames As String = "" Dim strCurrentName As String = "" While (xr.Read()) 'Read return false if we reach EOF If (xr.NodeType = XmlNodeType.Element AndAlso xr.Name = "Name") Then xr.Read() strCurrentName = xr.Value ElseIf (xr.NodeType = XmlNodeType.Element AndAlso xr.Name = "Result") Then xr.Read() If (xr.Value = "Passed") Then strPassedNames &= strCurrentName & vbCrLf End If End If End While MsgBox(strPassedNames) End Sub Code: 13.5 VB
12
Deccansoft Software Services
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
Deccansoft Software Services
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
Deccansoft Software Services
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
Deccansoft Software Services
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
Deccansoft Software Services MessageBox.Show(strNames); } Code: 13.7 C# Output:
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
View more...
Comments