locked
Linq to XML error handling RRS feed

  • Question

  • I have a method that navigates through several nodes to get to a value.  

    My problem is how do I check that all the nodes exist before navigating to the inner most one.   Because if the xml is not EXACTLY in the correct format it will raise an exception, whereas I just want to be able to check first that its valid and then navigate.

    The only way I can think of is to have several ugly IF statements that retrieve each node one by one null checking and then moving to the next one.

    This is my current code - however it will fail if one node is different:

    private bool ResponseErrorsMessage(string xml, IOffer offer)
            {
                bool result = true;

                XDocument rootDocument = XDocument.Parse(xml);
                XElement messageNode = rootDocument.Descendants
                    ("Response").Descendants
                    ("errors").Descendants
                    ("error").Descendants
                    ("message").First();

                if (messageNode != null)
                {
                    offer.ErrorMessage = messageNode.Value;
                    result = false;
                }

                return result;
            }
    Wednesday, July 29, 2009 4:29 PM

Answers

  • Why don't you validate the XML document against a schema before start retrieving nodes? Create a schema in vs.net out of the XML file. Then validate using XDocument.Validate() . Then start retrieving values. Actually this is the ideal way to do it.
    • Marked as answer by TheLearner Thursday, July 30, 2009 8:23 AM
    Wednesday, July 29, 2009 7:21 PM