Search code examples
c#xmlgetelementsbytagname

Get element from xml file in c#


I have an xml file which contains an element . i am storing the content of that xml file as string in csv in one of my projects.i am reading the content of that xml from csv and i want the data of the tag which exists in the content of xml file I tried like this.

XmlDocument doc = new XmlDocument();
doc.LoadXml(Convert.ToString(dataRow["XML"]));
var temp = doc.GetElementsByTagName("Mail");

but I am not getting the value of Mail into temp.what should i do?


Solution

  • GetElementsByTagName returns XmlNodeList. MSDN Reference

    // Display all the book titles.
    XmlNodeList elemList = doc.GetElementsByTagName("title");
    
    for (int i=0; i < elemList.Count; i++)
    {   
        Console.WriteLine(elemList[i].InnerXml);
    }  
    

    Linq solution:

    var xDoc = XDocument.Load(dataRow["XML"].ToString());
    
    var mailList = xDoc.Descendants("Mail")
                       .Select(x => new
                        {
                            MailID = x.Element("MailID").Value
                        })
                        .ToList();
    

    UPDATE:

    XmlDocument doc = new XmlDocument();
    doc.LoadXml(Convert.ToString(dataRow["XML"]));
    var temp = doc.GetElementsByTagName("Mail");
    
    // loop through all retrieved "Mail" elements 
    foreach(XmlElement xElem in temp)
    {
         string sMailText = xElem.InnerText;
    }