AndreyAkinshin
AndreyAkinshin

Reputation: 19031

How I can check an XmlReader can read content before calling Read()?

I read xml-string using XmlReader with code:

  XmlReader reader = XmlReader.Create(new StringReader(xmlString));      
  while (reader.Read())
  {
    // some code
  }

But if xmlString equal "" then I have XmlException on reader.Read(): root element not found. How I can check can XmlReader read content or not before reader.Read()?

Upvotes: 1

Views: 788

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039130

But if xmlString equal ""

Well, that's invalid XML, so it is an exceptional situation where it would be better to throw an exception rather than continuing to read something that is not what it pretends to be (XML). So you could simply catch this exception and inform the user that an error occurred. If he is responsible of the input string tell him that he entered invalid XML that cannot be processed. And if it is you, apologize by saying that something very bad went wrong.

This is to say that the XmlReader class expects a valid XML as input.

Upvotes: 7

Related Questions