0

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()?

2
  • What is you requirement here? Is the structure of xml fixed? And the name of the element you want to read, will that be known beforehand? Commented Nov 23, 2014 at 4:26
  • Yes the xml structure is fixed and the name of the element in this case "HTML" is known beforehand. Commented Nov 23, 2014 at 4:50

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

7 Comments

I modified my code as while (xmlr.Read()) { if ((xmlr.IsStartElement()) && (xmlr.Name == "HTML")) { xmlr.ReadToFollowing("HTML"); html = xmlr.ReadInnerXml(); } } But it will only get the value of <B>2.</B> Banana
Can you please paste the desired output in your question? Do you want the all the HTML elements as separate strings? You are getting a single HTML element and that is what you asked for right? If there are two elements you are overwriting the value every time in While loop. You should put html += xmlr.ReadInnerXMl() instead of html = xmlr.ReadInnerXml()
Ok actually i need to store all the html into a list var htmllist = new List<string>(); while (xmlr.Read()) { if ((xmlr.IsStartElement()) && (xmlr.Name == "HTML")) { xmlr.ReadToFollowing("HTML"); htmllist.Add(xmlr.ReadInnerXml()); } } So i only get Banana in the list.
Err sorry... I mean i only get banana in the list which is not correct... I need to get everything into the list. Your updated code will only get banana.
So are you not getting Apple in the list? I have updated the code again. If you are using .net 3.5(or above) and performance is not an issue than you can use LINQ which has better construct and easier options.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.