C# example to read soap message

by Jeff Fillegar on May 16, 2010

C# example to read soap message.
Task:  Read the following xml using c# and return the count of how many flights and the price and flight number from each flight element.

This is my sample xml:
<s:Envelope xmlns:s=”http://schemas.xmlsoap.org/soap/envelope/“>
            <GetFlightsResponse xmlns=”HP.SOAQ.SampleApp”>
                  <GetFlightsResult xmlns:i=”http://www.w3.org/2001/XMLSchema-instance“>
                              <ArrivalTime>04:17 PM</ArrivalTime>
                              <DepartureCity>Los Angeles</DepartureCity>
                              <DepartureTime>02:22 PM</DepartureTime>
                              <ArrivalTime>12:41 PM</ArrivalTime>
                              <DepartureCity>Los Angeles</DepartureCity>
                              <DepartureTime>10:46 AM</DepartureTime>
                              <ArrivalTime>11:29 AM</ArrivalTime>
                              <DepartureCity>Los Angeles</DepartureCity>
                              <DepartureTime>09:34 AM</DepartureTime>

Using C#and the XML DOM object, this is how it can be read and return:
1) Count of how many flight elements
2) Flight number
3) Price

C# code:
            String result = “”;

            XmlDocument doc = new XmlDocument();
            XmlNodeList flights = doc.GetElementsByTagName(“Flight”);

            result += “Flights count = ” + flights.Count + Environment.NewLine + “Flights: “;
            result += Environment.NewLine + “————————-“;

            foreach (XmlNode node in flights)
                XmlElement flightEle = (XmlElement)node;
                XmlNodeList flightNumbers = flightEle.GetElementsByTagName(“FlightNumber”);
                result += Environment.NewLine + “\tFlight #: ” + flightNumbers[0].InnerText;
                XmlNodeList prices = flightEle.GetElementsByTagName(“Price”);
                result += Environment.NewLine + “\tPrice:    ” + prices[0].InnerText;
                result += Environment.NewLine + “————————-“;


Leave a Comment

Previous post:

Next post: