I have a client that sends an xml feed which I parse using the following code. This code works.
reviews = from item in xmlDoc.Descendants("node")
select new ForewordReview()
{
PubDate = (string)item.Element("created"),
Isbn = (string)item.Element("isbn"),
Summary = (string)item.Element("review")
};
After getting all my “reviews” I cast the IEnumerable as a List and return it out. Originally, I was having a good and easy time parsing their XML which used to look like this:
<reviews>
<node>
<created>01-01-1900</created>
<ISBN>12345657890123</ISBN>
<Review>This is a nice and silly book</Review>
</node>
<node>
<created>01-01-2011</created>
<ISBN>1236245234554</ISBN>
<Review>This is a stupid book</Review>
</node>
<node>
<created>12-06-1942</created>
<ISBN>1234543234577</ISBN>
<Review>This is a old, naughty book</Review>
</node>
</reviews>
They have, however, changed their schema, to which I don’t have access, and now their XML is adding in a final <node> tag to the end which does not contain the decedent elements I am looking for, and so, my parsing breaks on this last tag and I throw an exception. Here is an example:
<reviews>
<node>
<created>01-01-1900</created>
<ISBN>12345657890123</ISBN>
<Review>This is a nice and silly book</Review>
</node>
<node>
<created>01-01-2011</created>
<ISBN>1236245234554</ISBN>
<Review>This is a stupid book</Review>
</node>
<node>
<created>12-06-1942</created>
<ISBN>1234543234577</ISBN>
<Review>This is a old, naughty book</Review>
</node>
<node>
<count>4656</count>
</node>
</reviews>
I need to know if there is a way to ignore this final tag (its always at the end of the document) even though it has the same name as all the other “node” tags I am looking for. I do have a try catch around this block of code but it doesnt return the list of good reviews out if it sees this error.
Thanks guys.
add null checking
Always add null checking to everything you do. Just good practice. In this case, it will eliminiate this error, but potentially crop up an error later in your program where you assume these strings are not empty, so make sure and null-check later as well.