如何使用C#从Web服务解析XML字符串

时间:2014-07-11 16:58:20

标签: c# xml web-services

在bovespa网站上有一个带有股票报价信息的网络服务

http://www.bmfbovespa.com.br/Pregao-Online/ExecutaAcaoAjax.asp?CodigoPapel=petr4

<ComportamentoPapeis>
    <Papel Codigo="PETR4" 
           Nome="PETROBRAS PN" 
           Ibovespa="#" 
           Data="10/07    /201400:00:00" 
           Abertura="17,78" 
           Minimo="0,00" 
           Maximo="18,17" 
           Medio="17,97" 
           Ultimo="18,11"      
           Oscilacao="4,50" 
           Minino="17,62"/>
</ComportamentoPapeis>

我正在尝试阅读此xml并使用以下代码导航到他:

using System;
using System.IO;
using System.Net;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace stock_analysis
{
    class Teste
    {
        public static void Main (string[] args)
        {
            const string URL = "http://www.bmfbovespa.com.br/Pregao-Online/ExecutaAcaoAjax.asp?CodigoPapel=petr4";
            // Create a request for the URL. 
            WebRequest request = WebRequest.Create (URL);
            // If required by the server, set the credentials.
            request.Credentials = CredentialCache.DefaultCredentials;
            // Get the response.
            WebResponse response = request.GetResponse ();
            // Display the status.
            //Console.WriteLine (((HttpWebResponse)response).StatusDescription);
            // Get the stream containing content returned by the server.
            Stream dataStream = response.GetResponseStream ();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader (dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd ();
            // Display the content.

            //Console.WriteLine (responseFromServer);
            // Clean up the streams and the response.

            //StringBuilder output = new StringBuilder();


            String xmlString = responseFromServer;

            //Console.WriteLine ("----\n {0}\n -------", xmlString);

            XElement xmlTree = XElement.Parse(xmlString);

            Console.WriteLine (xmlTree);

            reader.Close ();
            response.Close ();
        }
    }
}

如何导航到此XML?

1 个答案:

答案 0 :(得分:0)

阅读此MS文档以获取示例:

Querying an XDocument vs. Querying an XElement

它显示了2个选项。当然,您需要使用XElement.ParseXDocument.Parse代替Load