如何解析来自Web服务的数据

时间:2013-12-31 10:13:00

标签: c# windows-phone-7

我在windows phone 7应用程序中构建我的第一个应用程序。我可以使用添加服务引用方法从Web服务检索数据。我得到的输出是

<NewDataSet>
    <UserDetails>
        <id>1</id>
        <about_details>
            Arvind Kejriwal (born 16 August 1968) is an Indian social activist
            and politician. Born in Haryana, Kejriwal is a graduate of the Indian
            Institute of Technology Kharagpur, where he studied Mechanical 
            Engineering. He is a former Indian Revenue Service (IRS) officer and 
            former Joint Commissioner in the Income Tax Department. He is well-known
            for his role in drafting a proposed Jan Lokpal Bill and his efforts to 
            bring and implement the Right to Information (RTI) act at grassroots 
            level.
            Kejriwal was born in Hisar, Haryana, on 16 August 1968 in a Bania family 
            to Gobind Ram Kejriwal and Gita Devi, a well-educated and financially 
            well-off couple.
        </about_details>
    </UserDetails>
</NewDataSet>

现在我想只显示文本块中about_details中的文本。任何人都可以指导我如何做到这一点以及在何处放置代码。

   public about()
    {
        InitializeComponent();

        ServiceReference1.aapSoapClient client = new ServiceReference1.aapSoapClient();

        client.getarvindAboutCompleted += new EventHandler<ServiceReference1.getarvindAboutCompletedEventArgs>(client_getarvindAboutCompleted);

        client.getarvindAboutAsync();

    }



    void client_getarvindAboutCompleted(object sender, ServiceReference1.getarvindAboutCompletedEventArgs e)
    {

        textBlock1.Text = e.Result;
    }

2 个答案:

答案 0 :(得分:2)

假设您将数据作为单个字符串接收,解析它的最简单方法是使用XDocument类。

一个例子可能是:

var document = XDocument.Parse(response);
var aboutDetails = document.Element("NewDataSet")
                           .Element("UserDetails")
                           .Element("about_details")
                           .Value;

以上假设您的服务响应位于response变量中。你可能想要一个小错误检查,以避免抛出NullReferenceExceptions,但上面是一般的想法。

根据@ FunksMaName的评论以及上面的代码,以下内容应该可行:

void client_getarvindAboutCompleted(
    object sender, 
    ServiceReference1.getarvindAboutCompletedEventArgs e)
{
    var data = e.Result; 
    var xml = XElement.Parse(data); 
    var aboutDetails = xml.Element("UserDetails")
                          .Element("about_details")
                          .Value;
    textBlock1.Text = aboutDetails;
}

请注意,您需要确保项目已引用System.Xml.Linq。

答案 1 :(得分:0)

从工具中创建文本块。将其放在屏幕视图中。 让我们假设它的名字是textblock1。

获得文本后,请写入代码:

textblock1.Text=yourtext

yourtext可以是:

userDetails.about_details