Share via


XML Code Samples (Web SourceType)

This topic contains code samples that produces an XML request for the Web SourceType. For more information, see Web SourceType (Bing, Version 2).

Requirements

  • A deployment computer with an Internet connection

  • The ability to send requests using Hyper Text Transfer Protocol (HTTP 1.1)

  • The ability to parse XML

Demonstrates

These code samples demonstrate how to:

  • Send a request to the Bing XML interface and the Web SourceType

  • Display the Bing response as results

The samples are written in both Visual Basic and C#.

Example

Imports System
Imports System.Net
Imports System.Xml

' Bing API 2.0 code sample demonstrating the use of the
' Web SourceType over the XML Protocol.
Class WebSample

    ' Replace the following string with the AppId you received from the
    ' Bing Developer Center.
    Const AppId As String = "Insert your AppId here"

    Shared Sub Main()
        Dim request As HttpWebRequest = BuildRequest()
        Try
            ' Send the request; display the response.
            Dim response As HttpWebResponse = DirectCast( _
                request.GetResponse, _
                HttpWebResponse)
            DisplayResponse(response)
        Catch ex As WebException
            ' An exception occurred while accessing the network.
            Console.WriteLine(ex.Message)
        End Try
    End Sub

    Shared Function BuildRequest() As HttpWebRequest
        Dim requestString As String = "http://api.bing.net/xml.aspx?"

        ' Common request fields (required)
        requestString &= _
              "AppId=" & AppId _
            & "&Query=msdn blogs" _
            & "&Sources=Web"

        ' Common request fields (optional)
        requestString &= _
              "&Version=2.0" _
            & "&Market=en-us" _
            & "&Adult=Moderate" _
            & "&Options=EnableHighlighting"

        ' Web-specific request fields (optional)
        requestString &= _
              "&Web.Count=10" _
            & "&Web.Offset=0" _
            & "&Web.Options=DisableHostCollapsing+DisableQueryAlterations"

        ' Create and initialize the request.
        Dim request As HttpWebRequest = DirectCast( _
            WebRequest.Create(requestString), HttpWebRequest)

        Return request
    End Function

    Shared Sub DisplayResponse(ByVal response As HttpWebResponse)
        ' Load the response into an XmlDocument.
        Dim document As New XmlDocument
        document.Load(response.GetResponseStream)

        ' Add the default namespace to the namespace manager.
        Dim nsmgr As New XmlNamespaceManager(document.NameTable)
        nsmgr.AddNamespace( _
            "api", _
            "http://schemas.microsoft.com/LiveSearch/2008/04/XML/element")

        Dim errors As XmlNodeList = document.DocumentElement.SelectNodes( _
            "./api:Errors/api:Error", _
            nsmgr)

        If (errors.Count > 0) Then
            ' There are errors in the response. Display error details.
            DisplayErrors(errors)
        Else
            ' There were no errors in the response. Display the
            ' Web results.
            DisplayResults(document.DocumentElement, nsmgr)
        End If
    End Sub

    Shared Sub DisplayResults(ByVal root As XmlNode, _
        ByVal nsmgr As XmlNamespaceManager)

        ' Add the Web SourceType namespace to the namespace manager.
        nsmgr.AddNamespace( _
            "web", _
            "http://schemas.microsoft.com/LiveSearch/2008/04/XML/web")

        Dim web As XmlNode = root.SelectSingleNode("./web:Web", nsmgr)
        Dim results As XmlNodeList = web.SelectNodes( _
            "./web:Results/web:WebResult", _
            nsmgr)

        Dim version As String = root.SelectSingleNode( _
            "./@Version", _
            nsmgr).InnerText
        Dim searchTerms As String = root.SelectSingleNode( _
            "./api:Query/api:SearchTerms", _
            nsmgr).InnerText
        Dim offset As Integer
        Integer.TryParse( _
            web.SelectSingleNode("./web:Offset", nsmgr).InnerText, _
            offset)
        Dim total As Integer
        Integer.TryParse( _
            web.SelectSingleNode("./web:Total", nsmgr).InnerText, _
            total)

        ' Display the results header.
        Console.WriteLine("Bing API Version " & version)
        Console.WriteLine("Web results for " & searchTerms)
        Console.WriteLine( _
            "Displaying {0} to {1} of {2} results", _
            offset + 1, _
            offset + results.Count, _
            total)
        Console.WriteLine()

        ' Display the Web results.
        Dim builder As New System.Text.StringBuilder
        Dim result As XmlNode
        For Each result In results
            With result
                builder.Length = 0
                builder.AppendLine( _
                    .SelectSingleNode("./web:Title", nsmgr).InnerText)
                builder.AppendLine( _
                    .SelectSingleNode("./web:Url", nsmgr).InnerText)
                builder.AppendLine( _
                    .SelectSingleNode("./web:Description", nsmgr).InnerText)
                builder.Append("Last Crawled: ")
                builder.AppendLine( _
                    .SelectSingleNode("./web:DateTime", nsmgr).InnerText)

                DisplayTextWithHighlighting(builder.ToString)
                Console.WriteLine()
            End With
        Next
    End Sub

    Shared Sub DisplayTextWithHighlighting(ByVal [text] As String)
        ' Write text to the standard output stream, changing the console
        ' foreground color as highlighting characters are encountered.
        Dim c As Char
        For Each c In [text].ToCharArray
            If (c = Char.ConvertFromUtf32(&HE000)) Then
                ' If the current character is the begin highlighting
                ' character (U+E000), change the console foreground color
                ' to green.
                Console.ForegroundColor = ConsoleColor.Green
            ElseIf (c = Char.ConvertFromUtf32(&HE001)) Then
                ' If the current character is the end highlighting
                ' character (U+E001), revert the console foreground color
                ' to gray.
                Console.ForegroundColor = ConsoleColor.Gray
            Else
                Console.Write(c)
            End If
        Next
    End Sub

    Shared Sub DisplayErrors(ByVal errors As XmlNodeList)
        ' Iterate over the list of errors and display error details.
        Console.WriteLine("Errors:")
        Console.WriteLine()
        Dim [error] As XmlNode
        For Each [error] In errors
            Dim detail As XmlNode
            For Each detail In [error].ChildNodes
                Console.WriteLine(detail.Name & ": " & detail.InnerText)
            Next
            Console.WriteLine()
        Next
    End Sub

End Class
using System;
using System.Net;
using System.Xml;

// Bing API 2.0 code sample demonstrating the use of the
// Web SourceType over the XML Protocol.
static class WebSample
{
    // Replace the following string with the AppId you received from the
    // Bing Developer Center.
    const string AppId = "Insert your AppId here";

    static void Main()
    {
        HttpWebRequest request = BuildRequest();

        try
        {
            // Send the request; display the response.
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            DisplayResponse(response);
        }
        catch (WebException ex)
        {
            // An exception occurred while accessing the network.
            Console.WriteLine(ex.Message);
        }
    }

    static HttpWebRequest BuildRequest()
    {
        string requestString = "http://api.bing.net/xml.aspx?"

            // Common request fields (required)
            + "AppId=" + AppId
            + "&Query=msdn blogs"
            + "&Sources=Web"

            // Common request fields (optional)
            + "&Version=2.0"
            + "&Market=en-us"
            + "&Adult=Moderate"
            + "&Options=EnableHighlighting"

            // Web-specific request fields (optional)
            + "&Web.Count=10"
            + "&Web.Offset=0"
            + "&Web.Options=DisableHostCollapsing+DisableQueryAlterations";

        // Create and initialize the request.
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(
            requestString);

        return request;
    }

    static void DisplayResponse(HttpWebResponse response)
    {
        // Load the response into an XmlDocument.
        XmlDocument document = new XmlDocument();
        document.Load(response.GetResponseStream());

        // Add the default namespace to the namespace manager.
        XmlNamespaceManager nsmgr = new XmlNamespaceManager(
            document.NameTable);
        nsmgr.AddNamespace(
            "api",
            "http://schemas.microsoft.com/LiveSearch/2008/04/XML/element");

        XmlNodeList errors = document.DocumentElement.SelectNodes(
            "./api:Errors/api:Error",
            nsmgr);

        if (errors.Count > 0)
        {
            // There are errors in the response. Display error details.
            DisplayErrors(errors);
        }
        else
        {
            // There were no errors in the response. Display the
            // Web results.
            DisplayResults(document.DocumentElement, nsmgr);
        }
    }

    static void DisplayResults(XmlNode root, XmlNamespaceManager nsmgr)
    {
        // Add the Web SourceType namespace to the namespace manager.
        nsmgr.AddNamespace(
            "web",
            "http://schemas.microsoft.com/LiveSearch/2008/04/XML/web");

        XmlNode web = root.SelectSingleNode("./web:Web", nsmgr);
        XmlNodeList results = web.SelectNodes(
            "./web:Results/web:WebResult",
            nsmgr);

        string version = root.SelectSingleNode("./@Version", nsmgr).InnerText;
        string searchTerms = root.SelectSingleNode(
            "./api:Query/api:SearchTerms",
            nsmgr).InnerText;
        int offset;
        int.TryParse(
            web.SelectSingleNode("./web:Offset", nsmgr).InnerText,
            out offset);
        int total;
        int.TryParse(
            web.SelectSingleNode("./web:Total", nsmgr).InnerText,
            out total);

        // Display the results header.
        Console.WriteLine("Bing API Version " + version);
        Console.WriteLine("Web results for " + searchTerms);
        Console.WriteLine(
            "Displaying {0} to {1} of {2} results",
            offset + 1,
            offset + results.Count,
            total);
        Console.WriteLine();

        // Display the Web results.
        System.Text.StringBuilder builder = new System.Text.StringBuilder();
        foreach (XmlNode result in results)
        {
            builder.Length = 0;
            builder.AppendLine(
                result.SelectSingleNode("./web:Title", nsmgr).InnerText);
            builder.AppendLine(
                result.SelectSingleNode("./web:Url", nsmgr).InnerText);
            builder.AppendLine(
                result.SelectSingleNode("./web:Description", nsmgr).InnerText);
            builder.Append("Last Crawled: ");
            builder.AppendLine(
                result.SelectSingleNode("./web:DateTime", nsmgr).InnerText);

            DisplayTextWithHighlighting(builder.ToString());
            Console.WriteLine();
        }
    }

    static void DisplayTextWithHighlighting(string text)
    {
        // Write text to the standard output stream, changing the console
        // foreground color as highlighting characters are encountered.
        foreach (char c in text.ToCharArray())
        {
            if (c == '\uE000')
            {
                // If the current character is the begin highlighting
                // character (U+E000), change the console foreground color
                // to green.
                Console.ForegroundColor = ConsoleColor.Green;
            }
            else if (c == '\uE001')
            {
                // If the current character is the end highlighting
                // character (U+E001), revert the console foreground color
                // to gray.
                Console.ForegroundColor = ConsoleColor.Gray;
            }
            else
            {
                Console.Write(c);
            }
        }
    }

    static void DisplayErrors(XmlNodeList errors)
    {
        // Iterate over the list of errors and display error details.
        Console.WriteLine("Errors:");
        Console.WriteLine();
        foreach (XmlNode error in errors)
        {
            foreach (XmlNode detail in error.ChildNodes)
            {
                Console.WriteLine(detail.Name + ": " + detail.InnerText);
            }

            Console.WriteLine();
        }
    }
}