Tuesday, 21 April 2009

Extracting Attributes from XML file

suppose your xml is :
<entry>
<id>myid</id>
<published>mydate</published>
<updated>2009-04-20T22:42:23.233-07:00</updated>
<title type='text'>ASP.NET</title>
<summary type='html'></summary>
<link rel='self' type='application/atom+xml' href='#'/>
<link rel='alternate' type='text/html' href='#'/>
<link rel='http://schemas.my.com/g/2005#feed' type='application/atom+xml' href='#'/>
<link rel='http://schemas.my.com/g/2005#post' type='application/atom+xml' href='#'/>
<link rel='http://schemas.my.com/e' type='application/atom+xml' href='#'/>
<link rel='http://schemas.my.com/g/2008#settings' type='application/atom+xml' href='#'/>
<author>
<name>naresh</name>
<uri>http://www.naresh.com/profile</uri>
<email>noreply@blogger.com</email>
</author>
</entry>

This code read below xml attributes... Working fine.

void ReadXML()
{
XmlDocument xmldoc;

XmlNodeList xmlnodes;
DataSet dsxml = new DataSet();


dsxml = //using this if fill this dataset from database;
dsxml.ReadXml("write here xml path"); // if you have xml file then load xml file in dataset

if (dsxml.Tables.Count > 0)
{
xmldoc = new XmlDocument();
xmldoc.LoadXml(dsxml.GetXml());

xmlnodes = xmldoc.GetElementsByTagName("entry"); // here entry is element

XmlElement xmlel = null;

if (xmlnodes.Count > 0)
{
for (int k = 0; k < xmlnodes.Count; k++)
{
xmlel = xmlnodes[k]["link"];
string str_desc = "";
str_desc = getXmlItem(xmlnodes, "title", "", k);
}

}
}
}


object getXmlItem(XmlNodeList aItem, string aWhat, string aInitValue, int int_aItemIndex)
{
string tmpVar = aInitValue;

if ((aItem[int_aItemIndex][aWhat] != null) && (aItem[int_aItemIndex][aWhat] != null))
{
if ((aItem[int_aItemIndex][aWhat].FirstChild != null) && (aItem[int_aItemIndex][aWhat] != null))
{
tmpVar = aItem[int_aItemIndex][aWhat].FirstChild.Value;
}
}
return tmpVar;
}

No comments:

Post a Comment