Chapter 09

WORKING WITH XML

The XML Classes

The World Wide Web Consortium (W3C) has provided standards that defi ne the structure and provide a standard programming interface that can be used in a wide variety of environments and applications for XML documents. This is called the Document Object Model (DOM).

Classes that support the DOM are typically capable of random access navigation and modification of the XML document.

XmlDocument and XmlDataDocument

The XmlDocument and XmlDataDocument objects are in-memory representations of XML that use the DOM Level 1 and Level 2. These classes can be used to navigate and edit the XML nodes. The XmlDataDocument inherits from the XmlDocument and also represents relational data. The XmlDataDocument can expose its data as a DataSet to provide relational and nonrelational views of the data. The XmlDataDocument is in the System.Data.dll assembly.

XPathDocument

The XPathDocument provides a cached read-only XmlDocument that can be used for performing quick XPath queries. The constructor for this class requires a stream object to create an instance of this object. The only useful method that this class exposes is the CreateNavigator method.

XmlConvert

The XmlConvert class has many static methods for converting between XSD data types and common language runtime (CLR) data types. This class is especially important when working with data sources that allow names that are not valid XML names. If a column in a database table is called List Price, trying to create an element or attribute with a space character throws an exception. Using XmlConvert to encode the name converts the space to _0x0020_, so the XML element name becomes List_x0020_Price. Later, this name can be decoded using the XmlConvert.DecodeName method.

XmlConvert also provides many static methods for converting strings to numeric values.

XPathNavigator

DocumentNavigator provides efficient navigation of an XmlDocument by providing XPath support for navigation. XPathNavigator uses a cursor model and XPath queries to provide read-only random access to the data. XPathNavigator supports Extensible Stylesheet Language Transformations (XSLT) and can be used as the input to a transform.

XmlNodeReader

The XmlNodeReader provides forward-only access to data in an XmlDocument or XmlDataDocument. It provides the ability to start at a given node in the XmlDocument and sequentially read each node.

XmlTextReader The XmlTextReader provides noncached, forward-only access to XML data. It parses XML tokens but makes no attempt to represent the XML document as a DOM. The XmlTextReader does not perform document validation, but it checks the XML data to ensure that it is well formed.

XmlTextWriter

The XmlTextWriter provides noncached, forward-only writing of XML data to a stream of files, ensuring that the data conforms to the W3C XML 1.0 standard. The XmlTextWriter contains logic for working with namespaces and resolving namespace conflicts.

XmlReader

The XmlReader provides an object for reading and validating against DTD, XML Schema Reduced (XDR), or XSD. The constructor expects a reader or a string as the source of the XML to be validated.

XslTransform

The XslTransform can transform an XML document using an Extensible Stylesheet Language (XSL) stylesheet. The XslTransform supports XSLT 1.0 syntax and provides two methods: Load and Transform.

The Load method is used to load an XSLT stylesheet from a file or a stream. The Transform method is used to perform the transformation. The Transform method has several overloads but essentially expects an XmlDocument or XmlNode as the first argument, an XsltArgumentList, and an output stream.

Shembull 1:

1. Krijoni nje site te ri dhe vendosni ne te nje buton dhe nje label

2. Tek kodi i C# pergjegjes per site shtoni thirrjen per: using System.Xml;

3. Butonit ne design mode I jepni double click per te gjeneruar event handlerin

4. Ne funksionin e gjeneruar vendosni kodin e meposhtem:

protected void Button1_Click(object sender, EventArgs e)

{

//Declare and create new XmlDocument

XmlDocument xmlDoc = new XmlDocument();

XmlElement el;

int childCounter;

int grandChildCounter;

//Create the xml declaration first

xmlDoc.AppendChild(

xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null));

//Create the root node and append into doc

el = xmlDoc.CreateElement("myRoot");

xmlDoc.AppendChild(el);

//Child Loop

for (childCounter = 1; childCounter <= 4; childCounter++)

{

XmlElement childelmt;

XmlAttribute childattr;

//Create child with ID attribute

childelmt = xmlDoc.CreateElement("myChild");

childattr = xmlDoc.CreateAttribute("ID");

childattr.Value = childCounter.ToString();

childelmt.Attributes.Append(childattr);

//Append element into the root element

el.AppendChild(childelmt);

for (grandChildCounter = 1; grandChildCounter <= 3; grandChildCounter++)

{

//Create grandchildren

childelmt.AppendChild(xmlDoc.CreateElement("GrandChild"));

}

}

//Save to file

xmlDoc.Save(MapPath("XmlDocumentTest.xml"));

Label1.Text = "XmlDocumentTest.xml Created";

}

5. Vendosni ne site nje buton dhe nje label.

6. Butonit ne design mode I jepni double click per te gjeneruar event handlerin.

7. Ne funksionin e gjeneruar vendosni kodin e meposhtem:

protected void Button2_Click(object sender, EventArgs e)

{

XmlDocument xmlDoc = new XmlDocument();

xmlDoc.Load(MapPath("XmlDocumentTest.xml"));

RecurseNodes(xmlDoc.DocumentElement);

}

8. Shtoni ne kod funksionin e meposhtem:

public void RecurseNodes(XmlNode node)

{

//start recursive loop with level 0

RecurseNodes(node, 0);

}

9. Shtoni ne kod funksionin e meposhtem:

public void RecurseNodes(XmlNode node, int level)

{

string s;

s = string.Format("{0} <b>Type:</b>{1} <b>Name:</b>{2} <b>Attr:</b> ",

new string('-', level), node.NodeType, node.Name);

foreach (XmlAttribute attr in node.Attributes)

{

s += string.Format("{0}={1} ", attr.Name, attr.Value);

}

Label2.Text += s + "<br>";

foreach (XmlNode n in node.ChildNodes)

{

RecurseNodes(n, level + 1);

}

}

10. Tek kodi i C# pergjegjes per site shtoni thirrjen per: using System.Xml.XPath;

11. Vendosni ne site nje buton dhe nje label.

12. Butonit ne design mode I jepni double click per te gjeneruar event handlerin.

13. Ne funksionin e gjeneruar vendosni kodin e meposhtem:

protected void Button3_Click(object sender, EventArgs e)

{

XmlDocument xmlDoc = new XmlDocument();

xmlDoc.Load(MapPath("XmlDocumentTest.xml"));

XPathNavigator xpathNav = xmlDoc.CreateNavigator();

xpathNav.MoveToRoot();

RecurseNavNodes(xpathNav);

}

14. Shtoni ne kod funksionin e meposhtem:

public void RecurseNavNodes(XPathNavigator node)

{

//start recursive loop with level 0

RecurseNavNodes(node, 0);

}

15. Shtoni ne kod funksionin e meposhtem:

public void RecurseNavNodes(XPathNavigator node, int level)

{

string s = null;

s = string.Format("{0} <b>Type:</b>{1} <b>Name:</b>{2} <b>Attr:</b> ",

new string('-', level), node.NodeType, node.Name);

if (node.HasAttributes)

{

node.MoveToFirstAttribute();

do

{

s += string.Format("{0}={1} ", node.Name, node.Value);

} while (node.MoveToNextAttribute());

node.MoveToParent();

}

Label3.Text += s + "<br>";

if (node.HasChildren)

{

node.MoveToFirstChild();

do

{

RecurseNavNodes(node, level + 1);

} while (node.MoveToNext());

node.MoveToParent();

}

}

16. Krijoni : XmlSample.xml

<?xml version="1.0" encoding="utf-8"?>

<!DOCTYPE myRoot [

<!ELEMENT myRoot ANY>

<!ELEMENT myChild ANY>

<!ELEMENT myGrandChild EMPTY>

<!ATTLIST myChild

ChildID ID #REQUIRED

>

]>

<myRoot>

<myChild ChildID="ref-1">

<myGrandChild/>

<myGrandChild/>

<myGrandChild/>

</myChild>

<myChild ChildID="ref-2">

<myGrandChild/>

<myGrandChild/>

<myGrandChild/>

</myChild>

<myChild ChildID="ref-3">

<myGrandChild/>

<myGrandChild/>

<myGrandChild/>

</myChild>

<myChild ChildID="ref-4">

<myGrandChild/>

<myGrandChild/>

<myGrandChild/>

</myChild>

</myRoot>

17. Vendosni ne site nje buton dhe nje label.

18. Butonit ne design mode I jepni double click per te gjeneruar event handlerin.

19. Ne funksionin e gjeneruar vendosni kodin e meposhtem:

protected void Button4_Click(object sender, EventArgs e)

{

string s;

//Declare and create new XmlDocument

XmlDocument xmlDoc = new XmlDocument();

xmlDoc.Load(MapPath("XmlSample.xml"));

XmlNode node;

node = xmlDoc.GetElementById("ref-3");

s = string.Format("<b>Type:</b>{0} <b>Name:</b>{1} <b>Attr:</b>",

node.NodeType, node.Name);

foreach (XmlAttribute a in node.Attributes)

{

s += string.Format("{0}={1} ", a.Name, a.Value);

}

Label4.Text = s + "<br>";

}

20. Vendosni ne site nje buton dhe nje label.

21. Butonit ne design mode I jepni double click per te gjeneruar event handlerin.

22. Ne funksionin e gjeneruar vendosni kodin e meposhtem:

protected void Button5_Click(object sender, EventArgs e)

{

string s;

//Declare and create new XmlDocument

XmlDocument xmlDoc = new XmlDocument();

xmlDoc.Load(MapPath("XmlSample.xml"));

XmlNode node;

node = xmlDoc.SelectSingleNode("//myChild[@ChildID='ref-3']");

s = string.Format("<b>Type:</b>{0} <b>Name:</b>{1} <b>Attr:</b>",

node.NodeType, node.Name);

foreach (XmlAttribute a in node.Attributes)

{

s += string.Format("{0}={1} ", a.Name, a.Value);

}

Label5.Text = s + "<br>";

}

23. Vendosni ne site nje buton dhe nje label.

24. Butonit ne design mode I jepni double click per te gjeneruar event handlerin.

25. Ne funksionin e gjeneruar vendosni kodin e meposhtem:

protected void Button6_Click(object sender, EventArgs e)

{

string s;

//Declare and create new XmlDocument

XmlDocument xmlDoc = new XmlDocument();

xmlDoc.Load(MapPath("XmlSample.xml"));

XmlNodeList elmts;

elmts = xmlDoc.GetElementsByTagName("myGrandChild");

foreach (XmlNode node in elmts)

{

s = string.Format("<b>Type:</b>{0} <b>Name:</b>{1}",

node.NodeType, node.Name);

Label6.Text += s + "<br>";

}

}

26. Vendosni ne site nje buton dhe nje label.

27. Butonit ne design mode I jepni double click per te gjeneruar event handlerin.

28. Ne funksionin e gjeneruar vendosni kodin e meposhtem:

protected void Button7_Click(object sender, EventArgs e)

{

string s;

//Declare and create new XmlDocument

XmlDocument xmlDoc = new XmlDocument();

xmlDoc.Load(MapPath("XmlSample.xml"));

XmlNodeList elmts;

elmts = xmlDoc.SelectNodes("//myGrandChild");

foreach (XmlNode node in elmts)

{

s = string.Format("<b>Type:</b>{0} <b>Name:</b>{1}",

node.NodeType, node.Name);

Label7.Text += s + "<br>";

}

}

29. Vendosni ne site nje buton dhe nje label.

30. Butonit ne design mode I jepni double click per te gjeneruar event handlerin.

31. Ne funksionin e gjeneruar vendosni kodin e meposhtem:

protected void Button8_Click(object sender, EventArgs e)

{

string s;

XPathDocument xmlDoc = new XPathDocument(MapPath("XmlSample.xml"));

XPathNavigator nav = xmlDoc.CreateNavigator();

string expr = "//myChild[@ChildID='ref-3']";

//Display the selection.

XPathNodeIterator iterator = nav.Select(expr);

XPathNavigator navResult = iterator.Current;

while (iterator.MoveNext())

{

s = String.Format("<b>Type:</b>{0} <b>Name:</b>{1} ",

navResult.NodeType, navResult.Name);

if (navResult.HasAttributes)

{

navResult.MoveToFirstAttribute();

s += "<b>Attr:</b> ";

do

{

s += String.Format("{0}={1} ",

navResult.Name, navResult.Value);

}

while (navResult.MoveToNextAttribute());

}

Label8.Text += s + "<br>";

}

}

32. Vendosni ne site nje buton dhe nje label.

33. Butonit ne design mode I jepni double click per te gjeneruar event handlerin.

34. Ne funksionin e gjeneruar vendosni kodin e meposhtem:

protected void Button9_Click(object sender, EventArgs e)

{

string s;

XPathDocument xmlDoc = new XPathDocument(MapPath("XmlSample.xml"));

XPathNavigator nav = xmlDoc.CreateNavigator();

//Select all myChild elements

XPathExpression expr;

expr = nav.Compile("//myChild");

//Sort the selected books by title.

expr.AddSort("@ChildID", XmlSortOrder.Descending,

XmlCaseOrder.None, "",XmlDataType.Text);

//Display the selection.

XPathNodeIterator iterator = nav.Select(expr);

XPathNavigator navResult = iterator.Current;

while (iterator.MoveNext())

{

s = String.Format("<b>Type:</b>{0} <b>Name:</b>{1} ",

navResult.NodeType, navResult.Name);

if (navResult.HasAttributes)

{

navResult.MoveToFirstAttribute();

s += "<b>Attr:</b> ";

do

{

s += String.Format("{0}={1} ",

navResult.Name, navResult.Value);

} while (navResult.MoveToNextAttribute());

}

Label9.Text += s + "<br>";

}

}

35. Vendosni ne site nje buton.

36. Butonit ne design mode i jepni double click per te gjeneruar event handlerin.

37. Ne funksionin e gjeneruar vendosni kodin e meposhtem:

protected void Button10_Click(object sender, EventArgs e)

{

XmlTextWriter xmlWriter = new

XmlTextWriter(MapPath("EmployeeList.xml"),

System.Text.Encoding.UTF8);

xmlWriter.Formatting = Formatting.Indented;

xmlWriter.Indentation = 5;

xmlWriter.WriteStartDocument();

xmlWriter.WriteComment("XmlTextWriter Test Date: " +

DateTime.Now.ToShortDateString());

xmlWriter.WriteStartElement("EmployeeList");

//New Employee

xmlWriter.WriteStartElement("Employee");

xmlWriter.WriteAttributeString("EmpID", "1");

xmlWriter.WriteAttributeString("LastName", "JoeLast");

xmlWriter.WriteAttributeString("FirstName", "Joe");

xmlWriter.WriteAttributeString("Salary", XmlConvert.ToString(50000));

xmlWriter.WriteElementString("HireDate",XmlConvert.ToString(DateTime.Parse("1/1/2003"),

XmlDateTimeSerializationMode.Unspecified));

xmlWriter.WriteStartElement("Address");

xmlWriter.WriteElementString("Street1", "123 MyStreet");

xmlWriter.WriteElementString("Street2", "");

xmlWriter.WriteElementString("City", "MyCity");

xmlWriter.WriteElementString("State", "OH");

xmlWriter.WriteElementString("ZipCode", "12345");

//Address

xmlWriter.WriteEndElement();

//Employee

xmlWriter.WriteEndElement();

//New Employee

xmlWriter.WriteStartElement("Employee");

xmlWriter.WriteAttributeString("EmpID", "2");

xmlWriter.WriteAttributeString("LastName", "MaryLast");

xmlWriter.WriteAttributeString("FirstName", "Mary");

xmlWriter.WriteAttributeString("Salary", XmlConvert.ToString(40000));

xmlWriter.WriteElementString("HireDate",

XmlConvert.ToString(DateTime.Parse("1/2/2003"),

XmlDateTimeSerializationMode.Unspecified));

xmlWriter.WriteStartElement("Address");

xmlWriter.WriteElementString("Street1", "234 MyStreet");

xmlWriter.WriteElementString("Street2", "");

xmlWriter.WriteElementString("City", "MyCity");

xmlWriter.WriteElementString("State", "OH");

xmlWriter.WriteElementString("ZipCode", "23456");

//Address

xmlWriter.WriteEndElement();

//Employee

xmlWriter.WriteEndElement();

//EmployeeList

xmlWriter.WriteEndElement();

xmlWriter.Close();

Response.Redirect("EmployeeList.xml");

}

38. Vendosni ne site nje buton dhe nje label.

39. Butonit ne design mode I jepni double click per te gjeneruar event handlerin.

40. Ne funksionin e gjeneruar vendosni kodin e meposhtem:

protected void Button11_Click(object sender, EventArgs e)

{

XmlTextReader xmlReader = new

XmlTextReader(MapPath("EmployeeList.xml"));

while (xmlReader.Read())

{

switch (xmlReader.NodeType)

{

case XmlNodeType.XmlDeclaration:

case XmlNodeType.Element:

case XmlNodeType.Comment:

{

string s;

s = String.Format("{0}: {1} = {2}<br>",

xmlReader.NodeType,

xmlReader.Name,

xmlReader.Value);

Label11.Text += s;

break;

}

case XmlNodeType.Text:

{

string s;

s = String.Format(" - Value: {0}<br>",

xmlReader.Value);

Label11.Text += s;

break;

}

}

if (xmlReader.HasAttributes)

{

while (xmlReader.MoveToNextAttribute())

{

string s;

s = String.Format(" - Attribute: {0} = {1}<br>", xmlReader.Name, xmlReader.Value);

Label11.Text += s;

}

}

}

xmlReader.Close();

}

41. Vendosni ne site nje buton.

42. Butonit ne design mode I jepni double click per te gjeneruar event handlerin.

43. Ne funksionin e gjeneruar vendosni kodin e meposhtem:

protected void Button12_Click(object sender, EventArgs e)

{

//Declare and load new XmlDocument

XmlDocument xmlDoc = new XmlDocument();

xmlDoc.Load(MapPath("XmlSample.xml"));

//delete a node

XmlNode node;

node = xmlDoc.SelectSingleNode("//myChild[@ChildID='ref-3']");

node.ParentNode.RemoveChild(node);

//create a node and add it

XmlElement newElement =

xmlDoc.CreateElement("myNewElement");

node = xmlDoc.SelectSingleNode("//myChild[@ChildID='ref-1']");

node.ParentNode.InsertAfter(newElement, node);

xmlDoc.Save(MapPath("XmlSampleModified.xml"));

Response.Redirect("XmlSampleModified.xml");

}

44. Vendosni ne site dy butona.

45. Butonave ne design mode I jepni double click per te gjeneruar event handlerat.

46. Krijoni nje file: XmlBadSample.xml

47. File si me poshte:

<?xml version="1.0" encoding="utf-8"?>

<!DOCTYPE myRoot [

<!ELEMENT myRoot ANY>

<!ELEMENT myChild ANY>

<!ELEMENT myGrandChild EMPTY>

<!ATTLIST myChild

ChildID ID #REQUIRED

>

]>

<myRoot>

<myChild ChildID="ref-1">

<myGrandChild/>

<myGrandChild/>

<myGrandChild/>

</myChild>

<myChild ChildID="ref-2">

<myGrandChild/>

<myGrandChild/>

<myGrandChild>this is malformed</myGrandChild>

</myChild>

<myChild ChildID="ref-3">

<myGrandChild/>

<myGrandChild/>

<myGrandChild/>

</myChild>

<myChild ChildID="ref-4">

<myGrandChild/>

<myGrandChild/>

<myGrandChild/>

</myChild>

</myRoot>

48. Ne funksionet e gjeneruar vendosni kodin e meposhtem:

protected void Button13_Click(object sender, EventArgs e)

{

if (ValidateDocument(MapPath("XmlSample.xml")))

{

Label13.Text += "Valid Document<br />";

}

else

{

Label13.Text += "Invalid Document<br />";

}

}

protected void Button14_Click(object sender, EventArgs e)

{

if (ValidateDocument(MapPath("XmlBadSample.xml")))

{

Label14.Text += "Valid Document<br />";

}

else

{

Label14.Text += "Invalid Document<br />";

}

}

49. Shtoni funksionin:

private bool ValidateDocument(string fileName)

{

XmlReaderSettings xmlSet = new XmlReaderSettings();

xmlSet.ValidationType = ValidationType.DTD;

xmlSet.ProhibitDtd = false;

XmlReader vr = XmlReader.Create(fileName, xmlSet);

XmlDocument xd = new XmlDocument();

try

{

xd.Load(vr);

return true;

}

catch (Exception ex)

{

Label14.Text += ex.Message + "<br />";

return false;

}

finally

{

vr.Close();

}

}

/-----------------------------------------EXTRA----------------------------------------------/

Default.aspx

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"

CodeBehind="Default.aspx.cs" Inherits="chapter09._Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">

</asp:Content>

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">

<asp:GridView ID="GridView1" runat="server" AllowPaging="True"

AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333"

GridLines="None" AllowSorting="True" ShowHeader="False" TabIndex="3"

Font-Size="Medium" >

<AlternatingRowStyle BackColor="White" />

<Columns>

<asp:TemplateField>

<ItemTemplate>

<table>

<tr>

<td>

<asp:Button ID="button1" Width="120px" Height="50px" runat="server"

CausesValidation="false" Text='Kliko' ToolTip='<%# Eval("RegionDescription") %>'

onclick="button1_Click" />

</td>

</tr>

</table>

</ItemTemplate>

</asp:TemplateField>

</Columns>

<EditRowStyle BackColor="#2461BF" />

<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />

<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />

<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />

<RowStyle BackColor="#EFF3FB" />

<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />

<SortedAscendingCellStyle BackColor="#F5F7FB" />

<SortedAscendingHeaderStyle BackColor="#6D95E1" />

<SortedDescendingCellStyle BackColor="#E9EBEF" />

<SortedDescendingHeaderStyle BackColor="#4870BE" />

</asp:GridView>

<br />

<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

</asp:Content>

Default.aspx.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Data;

using System.Data.SqlClient;

using System.Configuration;

namespace chapter09

{

public partial class _Default : System.Web.UI.Page

{

public SqlConnection con;

public SqlCommand cmd;

protected void Page_Load(object sender, EventArgs e)

{

con = new SqlConnection("Data Source=GENA\\GENAINSTANCE; Initial Catalog=Northwind;user id=sa;password=12");

if (!IsPostBack)

{

GetData();

}

}

private void GetData()

{

cmd = new SqlCommand("SELECT * from Region", con);

SqlDataAdapter adap = new SqlDataAdapter(cmd);

DataTable dt = new DataTable();

adap.Fill(dt);

GridView1.DataSource = dt;

GridView1.DataBind();

}

protected void button1_Click(object sender, EventArgs e)

{

Button btn = (Button)sender;

string RegionName = btn.ToolTip;

Label1.Text= RegionName;

}

}

}