如何将url转换为XML

时间:2012-11-11 07:16:47

标签: c# xml web-services

我正在尝试使用此网址...

http://www.webservicex.net/stockquote.asmx/GetQuote?Symbol=T

它就像一个XML,但格式不正确,我希望能够用它以XML格式显示它......

这是我现在的代码

protected void btnGetResult_Click(object sender, EventArgs e)
{
    XPathNavigator nav;
    XmlDocument myXMLDocument = new XmlDocument();
    String stockQuote = "http://www.webservicex.net/stockquote.asmx/GetQuote?Symbol=T" + txtInfo.Text;
    myXMLDocument.Load(stockQuote);

    // Create a navigator to query with XPath.
    nav = myXMLDocument.CreateNavigator();
    nav.MoveToRoot();
    nav.MoveToFirstChild();

    do
    {
        //Find the first element.
        if (nav.NodeType == XPathNodeType.Element)
        {
            //Move to the first child.
            nav.MoveToFirstChild();

            //Loop through all the children.
            do
            {
                //Display the data.
                txtResults.Text = txtResults.Text + nav.Name + " - " + nav.Value + Environment.NewLine;
            } while (nav.MoveToNext());
        }
    } while (nav.MoveToNext());
}

1 个答案:

答案 0 :(得分:0)

查看您收到的回复来源。内容(使用rootnode的所有内容)都不是XML。标签是HTML实体:<>。直接加载到您的XmlDocument将把您之后的所有内容视为简单文本。

以下示例下载在线资源,用标记替换HTML实体并重新加载XML文档,然后由XPath访问。

string url = "http://www.webservicex.net/stockquote.asmx/GetQuote?Symbol=T";

XmlDocument doc = new XmlDocument();
doc.Load(url);

string actualXml = doc.OuterXml;
actualXml = actualXml.Replace("&lt;", "<");
actualXml = actualXml.Replace("&gt;", ">");
doc.LoadXml(actualXml);

我没有考虑您的示例源代码的第二部分。但我想有一个合适的XML文档将是第一步。