Parsing XML in C#


Since a lot of API responses are in XML, we'll review XML parsing in C# to help you get to the interesting data faster.

This tutorial assumes that you've already gone through our C# getting started tutorial and are familiar with how our C# SDK works.

Get an XML Response

1 Log in to Temboo and go to the Yahoo > Weather > GetWeatherByAddress Choreo in our Library.

2 Enter a location in the Address input and click Generate Code to test the Choreo from our website.

3 You get a whole bunch of XML in the Response output with lots of weather-related information about the location. Next we'll see how to parse through this response in C# and pick out only the pieces we're interested in.

Parse it in C#

4Create a new Visual Studio solution containing a "C# Console Application" project

5Make sure you've downloaded the Temboo C# SDK, and added TembooSDK.dll as a reference to your "C# Console Application" project as described in our getting started tutorial.

6Copy the code below into the Program.cs class of your Console Application Project. Steps 7, 8 and 9 talk you through what happens in the code.

using System;
using System.IO;
using System.Xml;
using System.Xml.XPath;
using Temboo.Core;
using Temboo.Library.Yahoo.Weather;

namespace TestProject
{
    class ParsingXML
    {
        static void Main(string[] args)
        {
            // Instantiate a TembooSession object using your Account name and Application key
            TembooSession session = new TembooSession("ACCOUNT_NAME", "APP_NAME", "APP_KEY");

            // Instantiate the Choreo using the TembooSession
            GetWeatherByAddress getWeatherByAddressChoreo = new GetWeatherByAddress(session);

            // Set inputs
            getWeatherByAddressChoreo.setAddress("104 Franklin St., New York NY 10013");

            // Execute Choreo
            GetWeatherByAddressResultSet getWeatherByAddressResults = getWeatherByAddressChoreo.execute();

            // Read the "Response" output from Yahoo into an XML document          
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(getWeatherByAddressResults.Response);

            // To parse data inside the XML that uses a namespace, we need to define
            // an XmlNamespaceManager object that knows about the namespace prefix(es)
            // that we care about.
            XmlNamespaceManager mgr = new XmlNamespaceManager(doc.NameTable);
            mgr.AddNamespace("yweather", "http://xml.weather.yahoo.com/ns/rss/1.0");

            // Select the first "yweather:condition" node out of the XML
            XmlNode node = doc.SelectSingleNode("//yweather:condition", mgr);

            // Extract the "text" and "temp" attributes from the node, and print them
            String text = node.Attributes["text"].Value;
            String temp = node.Attributes["temp"].Value;

            Console.WriteLine(text);
            Console.WriteLine(temp);

            // Wait for input, to prevent the Terminal from exiting immediately
            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }
    }
}

7 First we have to convert the XML response from Yahoo to an XMLDocument object.

8 Next we need to parse out the data we want from the XML file. It helps to look at the XML file's structure to get an idea of how it is organized. We want the text and temp attributes. You can find them in:

<channel><yweather:condition>

This element is in an XML namespace (indicated by the ":" in the element name). To parse namespaced elements, it's necessary to create an XmlNamespaceManager, and populate it with the name and schema URL of the namespace. You can find this information in the XML header.

9 After defining the XmlNamespaceManager, we can select the node we care about and extract the text and temp attributes.

10That's it. You can run the code to try it out. You should see the weather condition text and temp printed in the console.

What next?

Now you're ready to tackle all sorts of XML parsing tasks. Check out the 2000+ Choreos in our Library and find some exciting data to parse.

Once you've got your code up and running, you're ready to move on and do more. From monitoring your running applications, to moving your generated Temboo code to your preferred development environment and sharing it with colleagues, collaborators and friends - we've got you covered.

Commit Code to GitHub

Commit Temboo-generated code directly to GitHub and share with the world. Learn more.

Need help?

We're always happy to help. Just email us at support@temboo.com, and we'll answer your questions.


Back