Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking XML for expected structure

Tags:

c#

validation

xml

I am calling a function which returns a string containing XML data. How this function works is not important but the resulting xml can be different depending on the success of the function.

Basically the function will return either the expect XML or an error formatted XML. Below are basic samples of what the two results might look like...

On Success:

<SpecificResult>
    <Something>data</Something>
</SpecificResult>

On Error:

<ErrorResult>
    <ErrorCode>1</ErrorCode>
    <ErrorMessage>An Error</ErrorMessage>
</ErrorResult>

The way my system is set up is that I can convert an xml string to a class with a simple converter function but this requires my to know the class type. On success, I will know it is SpecificResult and I can convert. But I want to check to first if an error occured.

The ideal end result would allow something similar to this...

string xml = GetXML();
if(!IsError(xml))
{
   //convert to known type and process
}

So the question is, what is the best way to implement the IsError function?

I have thought of a couple of options but not sure if I like any of them really...

  1. check if xml string contains "<ErrorResult>"
  2. try to convert xml to ErrorResult class and check for fail
  3. use XDocument or similar built in functions to parse the tree and search for ErrorResult node
like image 417
musefan Avatar asked Feb 01 '12 12:02

musefan


1 Answers

Since the GetXml() method is essentially returning untyped data and the only safe assumption here is that it's structured as XML, the safest way to assert its actual type would be to parse it as XML:

private bool IsError(string xml)
{
    var document = XDocument.Parse(xml);
    return document.Element("ErrorResult") != null;
}
like image 127
Enrico Campidoglio Avatar answered Oct 21 '22 15:10

Enrico Campidoglio