XML
MIS 21 – Introduction to Applications Development
Outline
XML intro
XML Document
XML & C#
Load,Display, Add, Update, Delete,
Create
XML
Stands for Extensible Markup Language
Allowsusers to store and describe data
using simple text files through the use of
tags.
Is software and hardware independent
Makes data more available to any system or any
platform that can read text files
XML Document
Refers to a complete set of data in XML
format
Contains
nodes, referring to different parts
of an XML document
Different kinds of nodes
XML Declaration
XML Elements
Text within XML Elements
Attributes
XML Document
<?xml version="1.0" encoding="utf-8"?> Declaration
<playlist genre="90's Grunge">
<song>
Attributes
<title>Porch</title>
<artist>Pearl Jam</artist> name="…"
<album>Ten</album>
</song> Elements
<song>
<title>Crackerman</title> <…> value </…>
<artist>Stone Temple Pilots</artist>
<album>Core</album>
</song> Text within
</playlist> elements
XML Declaration
Occurs in every XML document
Contains what version of XML is used,
encoding, and any other part related to
the particular XML document
Example
<?xml version="1.0" encoding="utf-8" ?>
XML Element
Contains an opening tag, data, and closing tag
<artist>Pearl Jam</artist>
Tags are case sensitive
Can contain other elements but tags of all sub-
elements must be closed before parent element is
closed <item>
<song>Porch</song>
<artist>Pearl Jam</artist>
<album>Ten</album>
</item>
Attributes
Alternative
place to store data instead
of XML element body
Placedin the opening tag of an XML
element
Should have a name, an =, and the
data enclosed in ""
<playlist genre="90's Grunge">
XML Document Structure
Hierarchical/Tree, similar to Windows
Explorer folders and files
Contains the following:
XML declaration
XML Root element (an element which
contains all the succeeding elements)
XML elements and sub-elements (may or
may not contain attributes)
XML and C#
Basic pattern for using XML with C#
Load XML file
Do something with XML data
Display XML elements
Add XML elements
Update XML elements
Delete XML elements
Save the XML file
Loading XML Files
Use the following classes
XmlDocument (represents the Xml document)
XmlNode (represents any kind of Xml node)
Steps:
1. Create an instance of XmlDocument
2. Call the load() of XmlDocument
3. Create an instance of XmlNode and let it be a
reference to the root element. Use the
DocumentElement property of XmlDocument
Loading XML Files
Sample code
XmlDocument document = new XmlDocument();
document.Load(path);
XmlNode root = document.DocumentElement;
Tips
Put complete path for the Xml Document for proper
loading
Do not forget to instantiate the root element of the
document, all other elements will be derived from this
Display XML Elements
Use the following classes
XmlNodeList (arraylist of XmlNodes)
XmlNode
Usethe ChildNodes property of the root
XmlNode to get all child nodes, this returns
an XmlNodeList object
Iteratethrough the XmlNodeList object to
print/ access data
Display XML Elements
The following properties are useful in
printing data contained in an XmlNode:
InnerXml (prints the tags + value between tags)
InnerText (prints value between tags only)
Name (prints value inside tag)
Display XML Elements
InnerXml
Assuming song was instantiated as an
XmlNode, InnerXml will return those in
bold as 1 concatenated string
<song>
<title>Crackerman</title>
<artist>Stone Temple Pilots</artist>
<album>Core</album>
</song>
Display XML Elements
InnerText
Assuming song was instantiated as an
XmlNode, InnerText will return those in
bold as 1 concatenated string
<song>
<title>Crackerman</title>
<artist>Stone Temple Pilots</artist>
<album>Core</album>
</song>
Display XML Elements
XmlNode
Assuming song was instantiated as an
XmlNode, Name will return those in bold
as 1 concatenated string
<song>
<title>Crackerman</title>
<artist>Stone Temple Pilots</artist>
<album>Core</album>
</song>
Display XML Elements
Sample Code
XmlNodeList songs = root.ChildNodes;
for (int x = 0; x < songs.Count; x++)
{
XmlNode song = songs[x];
XmlNodeList songNodes = song.ChildNodes;
string[] songRow = new string[songNodes.Count];
for (int i = 0; i < songNodes.Count; i++)
{
XmlNode songNode = songNodes[i];
songRow[i] = songNode.InnerText;
}
foreach(string s in songRow)
{ Console.WriteLine(s);
}
}
Display XML Elements
Itis possible to go deeper into the
document. Use the following to access
child nodes of any XmlNode:
ChildNodes, FirstChild, LastChild,
NextSibling
Attributesmay be printed by following
the same structure but using
XmlAttribute instead of XmlNode.
Add XML Elements
Use the following classes
XmlNode
XmlElement (represents the tags)
XmlTextNode (represents the value between
tags
Add XML Elements
Steps:
1. Create XmlElements to represent its children,
use CreateElement() for this
2. Create XmlTextNodes to represent the values
using CreateTextNode()
3. Associate each XmlTextNode to its respective
XmlElement using the AppendChild() of the
XmlElement objects
Add XML Elements
Steps:
4. Create an XmlElement to represent the parent
node using the CreateElement() method of the
XmlDocument object
5. Append the child XmlElement objects to the
parent XmlElement object using AppendChild()
of the parent XmlElement
6. Append the parent XmlElement object to the
root element using AppendChild() of the root
element
Add XML Elements
Sample code
XmlElement newTitle = document.CreateElement("artist");
XmlText newTitleText = document.CreateTextNode(artist);
newTitle.AppendChild(newTitleText);
...
XmlElement newSong = document.CreateElement("song");
newSong.AppendChild(newTitle);
newSong.AppendChild(newArtist);
newSong.AppendChild(newAlbum);
root.AppendChild(newSong);
Add XML Elements
XmlElement and XmlText are both derived
from XmlNode, so technically an XmlNode
object may receive the objects returned by
CreateElement() and CreateTextNode()
Always append
Text values to child elements
Child elements to parent elements
Parent elements to root element
Update XML Elements
Steps:
1. Identify the XmlNode with values to
modify
2. Identify the XmlElements within the
XmlNode whose value is to be changed
3. Change the value of by using the
InnerText property.
Update XML Elements
Sample code
String searchTitle = Console.ReadLine();
XmlNodeList children = root.ChildNodes;
for (int x = 0; x < children.Count; x++)
{
XmlNode song = children[x];
string songTitle = song.ChildNodes[1].InnerText;
if (songTitle.Equals(searchTitle))
{
song.ChildNodes[0].InnerText = newArtist;
song.ChildNodes[1].InnerText = newTitle;
song.ChildNodes[2].InnerText = newAlbum;
break; // exit the loop
}
}
Delete XML Elements
Steps:
1. Identify XmlElement to delete
2. Use the RemoveChild() of the parent
XmlNode to remove XmlElement
Delete XML Elements
Sample code
XmlNodeList children = root.ChildNodes;
for (int x = 0; x < children.Count; x++)
{
XmlNode song = children[x];
string songTitle = song.ChildNodes[1].InnerText;
if (songTitle.Equals(deleteTitle))
{
root.RemoveChild(song);
break; // exit the loop
}
}
Save the XML File
Write the contents of an XmlDocument
using Save()
Steps:
1. Identify the path of the XML document
2. Use the Save() of the XmlDocument
object
Save the XML File
Sample code
document.Save(path);
Call
after adding, updating or deleting
XML elements
Use the same file called in
document.Load() to overwrite the old
data with the new data
Creating an XML document
Sometimes, there is a need to Create
an XML file
Steps:
1. Create the document
2. Create the root element
3. Append the root to the document
4. Append everything else to the root
Creating an XML document
Sample Code
static void Main(string[] args)
{
XmlDocument document = new XmlDocument();
XmlNode root = document.CreateElement("songs");
document.AppendChild(root);
//code to create other elements
//code to append other elements to the root
}