Lesson 12: XML with CSharp



 

XML

Image Credit: commons.wikimedia.org

XML with C#

XML(Extensible Markup Language),in its simplest form,can be defined as the container of data with user specified tags.
The difference between XML document and HTML document is that the HTML document is used for the display purpose.It mainly deals with the way of designing the user interface to the end user.HTML tags are predefined not user defined.
On the other hand ,XML document contains data which HTML does not.XML is not concerned with the visual representation of the data like HTML. Furthermore, XML tags are user defined.XML document is used to carry or transfer the data which it contains.
Both XML and HTML comes under the category of Markup Languages.The SGML or Standard Generalized Markup Language is the superset of both.It means that the markup languages are written in the light of SGML in order to provide a proper documentation.
The main purpose of XML is that,it can be transferred to databases such as Sql Server,MySql ,Oracle etc because it is not dependent upon a specific technology.

Well Formed vs Valid Document

Well formed document means that our XML is free from syntax errors, spelling mistakes,grammatical errors etc. in its markup.

Example

<?xml version=”1.0″ encoding=”ISO-8859-1″?>
<company>
<department>Marketing</department>
<employeename>George</employeename>
<position>Manager</position>
</company>

 

Valid Document

A Valid Document is a well formed document which follows DTD(Document Type definition)

Example
<!DOCTYPE HTML >
<?xml version=”1.0″ encoding=”ISO-8859-1″?>
<company>
<department>Marketing</department>
<employeename>George</employeename>
<position>Manager</position>
</company>
 

DTD

A Document Type definition is a file that describes the syntax of SGML languages.
The which is used in the above example, describes the browser about which version of HTML it is targeting

DOM

The XML DOM (Document Object Model) underlines the proper way to access or manipulate XML document(s).
The XML document has to appear in the form of hierarchical structure in order to fulfill the DOM requirements.

I have taken this image as a reference from XML

Explanation:

The first line <?xml version=”1.0″> </> is a declaration of xml version.We may include
<?xml version=”1.0″ encoding=”UTF-8″?> to make sure that our xml file follows “UTF-8″ encoding which is standard.

<?xml version=”1.0″/>
<catalog>
<book id=”bk101″>
<author>Gambardella, Matthew</author>
<title>XML Developer’s Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications
with XML.</description>
</book>
<book id=”bk102”>
<author>Ralls, Kim</author>
<title>Midnight Rain</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-12-16</publish_date>
<description>A former architect battles corporate zombies,
an evil sorceress, and her own childhood to become queen
of the world.</description>
</book>
.
.
.
.
</catalog>

In the above XML markup,the catalog is the root element and within it,other child elements are present.The root element occurs only once.The <strong>document element</strong> is another name for root element.The first child i.e <book id=”bk101″>
has book an element and id its attribute.Always follow proper guidelines of formatting and placing the contents well because unlike html;xml does not forgive you.The book element closes with </book> tag.

<author>Gambardella, Matthew</author>
<title>XML Developer’s Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications
with XML.</description>
All of the above mentioned tags are the children of <catalog> root node.The tag <author>Gambardella, Matthew</author> has an author as an element and inside it “Gambardella, Matthew” is its text.

Using attributes is not considered a good practice due to their limitations of containing no more than one value.They are difficult to Parse as well

What is XML Parsing?

Parsing is done to read the contents of an XML file as per requirement.


Examples of XML with C#

//Creating an xml file

using System;
using System.Xml;// To reference Xml Objects

class Program {
static void Main( )
{

//Creating an object XmlDoc of XmlDocument
XmlDocument XmlDoc = new XmlDocument();

//Creating XmlElements named as XmlElement1, XmlElement
XmlElement XmlElement1 = XmlDoc.CreateElement( “”, “book”, “” );
XmlDoc.AppendChild( XmlElement1 );

XmlElement XmlElement2 = XmlDoc.CreateElement( “”, “genre”, “” );
//Add genre as a child element to the book element
XmlElement1.AppendChild( XmlElement2 );

//Creating element comic
XmlElement XmlElement3 = XmlDoc.CreateElement( “”, “comic”, “” );

//element comic has text in it which writes superman
XmlText comictext = XmlDoc.CreateTextNode( “superman” );

XmlElement3.AppendChild( comictext );
XmlElement2.AppendChild( XmlElement3 );

XmlElement XmlElement4 = XmlDoc.CreateElement( “”, “horror”, “” );
XmlText mysterytext = XmlDoc.CreateTextNode( “dracula” );
XmlElement4.AppendChild( mysterytext );
XmlElement2.AppendChild( XmlElement4 );
//save the document to drive E: with the name books.xml
XmlDoc.Save( “E:books.xml” );
}
}

Output

Reading from already created file

using System;
using System.Xml;

class Program
{
static void Main()
{

/*The text xmlReader object extracts the contents of an
XML file in a forward only fashion.So it is faster */
XmlTextReader xmlReader = new XmlTextReader(“E:books.xml”);

//Loop until the the file has contents
while (xmlReader.Read())
{

switch (xmlReader.NodeType)
{
case XmlNodeType.Element:
Console.Write(“Element :<" + xmlReader.Name); Console.WriteLine(">“);
break;
case XmlNodeType.Text:
Console.WriteLine(“Text:” + xmlReader.Value);
break;
case XmlNodeType.EndElement:
Console.Write(“End Element:“);
break;
}
}
Console.ReadLine();
}
}

Output

The above procedure also known as “Parsing”

Example:Here is the file used in the example below

using System;
using System.Xml;
using System.Xml.XPath;

class Program
{
static void Main()
{
XPathQuery();
}

private static void XPathQuery()
{

try
{
XPathDocument xmlDocument = new XPathDocument(“E:books.xml”);
XPathNavigator xmlNavigator = xmlDocument.CreateNavigator();

XPathExpression xmlExpr;
xmlExpr = xmlNavigator.Compile(“/book/genre/title”);
XPathNodeIterator iterator = xmlNavigator.Select(xmlExpr);

Console.WriteLine(“Iterating with XPath Expressn”);
while (iterator.MoveNext())
{
XPathNavigator xpathNav = iterator.Current.Clone();

Console.WriteLine(“Title:{0}n”, xpathNav.Value);

}

Console.ReadKey();
}

catch(Exception ex)
{

Console.WriteLine(ex.Message);

}

}
}

Output

XPath Expressions

Deleting the node

using System;
using System.Xml;
using System.Xml.XPath;

/*

The xml file is hospital.xml
*
* It has the following markup
*
*
Dr. George
Neuro Psychiatry
101
Dr. Smith
Orthopaedics
102

*

*/

class Program
{
static void Main()
{

XmlDocument myDocument = new XmlDocument();
myDocument.Load(“E:hospital.xml”);

XmlNode selectedNode = myDocument.SelectSingleNode(“/hospital/physician[room=102]”);
selectedNode.RemoveAll();

XmlNode ancestorNode = selectedNode.ParentNode;
ancestorNode.RemoveChild(selectedNode);
myDocument.Save(“E:hospital.xml”);
}

}

Output

See by yourself

Search by an attribute
Example file is here :

using System;
using System.Xml;
using System.Xml.XPath;

class XMLQueries
{

static void Main()
{

XPathDocument XPathDoc = new XPathDocument(“E:hospital.xml”);

XPathNavigator XPathSeeker = XPathDoc.CreateNavigator();

XMLFindDoctor(XPathSeeker);

Console.ReadKey();

}

public static void XMLFindDoctor(XPathNavigator XPathSeeker2)
{

XPathNodeIterator nodeIterator = XPathSeeker2.Select(“//Hospital/Physician[@Title=’ Specialist’]”);

if (nodeIterator.Count > 0)
{

while (nodeIterator.MoveNext())
{
Console.WriteLine(nodeIterator.Current);
}
}
else
{
Console.WriteLine(“Sorry! No record found”);
return;

}

}

}

Output

Dr-George Neuro Psychiatry 101
Dr.John Oncologist 102

Adding and Editing examples will be shown when we use LINQ to XML but right now, you have learned XML with C#

Lesson 12 Completed…..


Syed Adeel Ahmed
Analyst, Programmer, Educationist and Blogger at Technofranchise
Computer Systems Engineer from Sir Syed University Of Engineering & Technology.I am passionate about all types of programming.
Syed Adeel Ahmed on FacebookSyed Adeel Ahmed on GoogleSyed Adeel Ahmed on InstagramSyed Adeel Ahmed on Twitter

Published by

Syed Adeel Ahmed

Computer Systems Engineer from Sir Syed University Of Engineering & Technology.I am passionate about all types of programming.