使用WCF服务时出现问题

时间:2012-12-28 08:32:15

标签: wcf linq

在我的应用程序中,我有一个WCF REST服务,可以通过我的silverlight客户端进行调用。

private void btnGetEmployees_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            WebClient wClient = new WebClient();
            wClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wClient_OpenReadCompleted);
            wClient.DownloadStringAsync(new Uri("http://localhost/DummyService/Service.svc/EmpRest", UriKind.Absolute));
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

void wClient_OpenReadCompleted(object sender, DownloadStringCompletedEventArgs e)
    { 
XDocument xdStudent = XDocument.Parse(e.Result);
var Result = (from emp in xdStudent.Descendants("Employee")
                          select new Employee
                          {
                             EmpNo = emp.Element("EmpNo").Value,
                             EmpName = emp.Element("EmpName").Value
                          }
                          ).ToList();

            dgData.ItemsSource = Result;
}

我可以从e.Result获得POX结果。以下是样本结果

<ArrayOfEmployee xmlns="http://schemas.datacontract.org/2004/07/WCF_REST_Service" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Employee>
<EmpName>Emp_1</EmpName>
<EmpNo>101</EmpNo>
</Employee>
<Employee>
<EmpName>Emp_2</EmpName>
<EmpNo>102</EmpNo>
</Employee>
<Employee>
<EmpName>Emp_3</EmpName>
<EmpNo>103</EmpNo>
</Employee>
 <Employee>
<EmpName>Emp_4</EmpName>
<EmpNo>104</EmpNo>
</Employee>
<Employee>
<EmpName>Emp_5</EmpName>
<EmpNo>105</EmpNo>
</Employee>
</ArrayOfEmployee>

但是当我使用LINQ查询XDocument时,我没有收到结果。我出于测试目的,手动加载了XDocument(不是来自服务),如下所示,并且能够获取值。

string xml = @"
            <ArrayOfEmployee >
              <Employee>
                <EmpName>Emp_1</EmpName>
                <EmpNo>101</EmpNo>
              </Employee>
              <Employee>
                <EmpName>Emp_2</EmpName>
                <EmpNo>102</EmpNo>
              </Employee>
              <Employee>
                <EmpName>Emp_3</EmpName>
                <EmpNo>103</EmpNo>
              </Employee>
              <Employee>
                <EmpName>Emp_4</EmpName>
                <EmpNo>104</EmpNo>
              </Employee>
              <Employee>
                <EmpName>Emp_5</EmpName>
                <EmpNo>105</EmpNo>
              </Employee>
            </ArrayOfEmployee>";
            XDocument xdStudent = XDocument.Parse(xml); 

我做的唯一更改是从根标记中删除属性

xmlns="http://schemas.datacontract.org/2004/07/WCF_REST_Service" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"

我认为当我使用LINQ查询XDocument时,这些属性会引发解析问题。

1 个答案:

答案 0 :(得分:0)

您的问题与WCF无关,只涉及您的XML解析。您在测试示例中删除的“属性”是文档的命名空间,解析需要命名空间来标识节点。在您的测试用例中,您要求Linq解析没有命名空间的元素,而不是具有完全限定名称的元素

http://schemas.datacontract.org/2004/07/WCF_REST_Service:Employee

因此,严格来说,您的测试与您的生活场景完全不同。

看看at this question about Linq to XML