Search code examples
c#xmlxml-parsingxmlreader

C# XMLReader ReadString how to read everything include nested xml in an element?


My xml file with sample data as following

 <FRUIT>
 <HTML><B>1.</B> Apple</HTML>
 <HTML><B>2.</B> Banana</HTML>
 </FRUIT>

and my code

XmlReader xmlr = XmlReader.Create(myxmlfile);
while (xmlr.Read())
{
  if ((xmlr.IsStartElement()) && (xmlr.Name == "HTML"))
  {
    // this will return blank string!
    html = xmlr.ReadString();
  }
}

I need to get the full string of <B>1.</B> Apple

How could I read everything inside HTML element with ReadString()?


Solution

  • If the structure is fixed and you know the elements before then you can do this:

     List<string> bananas = new List<>string();
     string contents = string.Empty;
        xmlr.ReadToFollowing("HTML");
        do
        {   
            contents = xmlr.ReadInnerXML();
            if(!string.IsNullOrEmpty(contents))
            {        
                bananas.Add(contents);  
            }
    
        }while(!string.IsNullOrEmpty(contents))
    

    Also read XMLReader on MSDN