Monday, July 11, 2011

Parse XML string sample

There are five main techniques to parse xml files. Each technique is based on a different .NET Framework class and its associated methods:

  • XmlTextReader
  • XmlDocument
  • XPathDocument
  • XmlSerializer
  • DataSet

In the following sample I will explain how to perform this using xmlDocument


string sXML = "" +
"<LostFound MyFormID= \"12 \"> " +
"<FormID>12</FormID>" +
" <LostFoundLogic> " +
" <TargetTypeID>1</TargetTypeID> " +
" <TargetID>2</TargetID> " +

" </LostFoundLogic> " +
" " +
" <LostFoundLogic> " +
" <TargetTypeID>111</TargetTypeID> " +
" <TargetID>222</TargetID> " +

" </LostFoundLogic> " +

"</LostFound> ";


XmlNode objNode = null;
string strXml = sXML;
if (strXml.Length > 0)
{
XmlDocument select = new XmlDocument();
select.LoadXml(strXml);
XmlNodeList LostFoundList = select.GetElementsByTagName("LostFoundLogic");


foreach (XmlNode anode in LostFoundList)

{
objNode = anode.SelectSingleNode("TargetTypeID"); if (objNode != null)
{

int TargetTypeID = Convert.ToInt32(anode.SelectSingleNode("TargetTypeID").InnerText);

}
int TargetID = Convert.ToInt32(anode.SelectSingleNode("TargetID").InnerText);
}

XmlNode node;

node = select.SelectSingleNode("/LostFound/FormID");

string FormID = node.InnerText;



//Retreieve MyFormID attribute
XmlNode dsEventType = xmlDiary.GetElementsByTagName("LostFound")[0];
sEventType = dsEventType.Attributes[ MyFormID"].Value + "";

}

No comments:

Post a Comment

Open default email app in .NET MAUI

Sample Code:  if (Email.Default.IsComposeSupported) {     string subject = "Hello!";     string body = "Excellent!";    ...