解析WCF WebHttp服务的结果

时间:2011-05-10 15:27:55

标签: wcf linq-to-xml

我有一个非常简单的WCF服务运行,它返回以下内容(来自一个基本的新项目)xml:

  <ArrayOfSampleItem xmlns="http://schemas.datacontract.org/2004/07/WcfRestService1" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
     <SampleItem>
         <Id>1</Id>
         <StringValue>Hello</StringValue>
     </SampleItem>
  </ArrayOfSampleItem>

然后我在Windows Phone 7应用程序中使用它。结果很好但是我在解析xml时遇到了问题。这是我在完成请求后在回调中使用的代码:

        XDocument xmlDoc = XDocument.Parse(e.Result);

        itemsFetched.ItemsSource = from item in xmlDoc.Descendants("SampleItem")
                                   select new Product()
                                              {
                                                  Id = item.Element("Id").Value,
                                                  StringValue = item.Element("StringValue").Value
                                              };

当我尝试添加名称空间时,不会使用此填充集合:

        XNamespace web = "http://schemas.datacontract.org/2004/07/WcfRestService1";

        XDocument xmlDoc = XDocument.Parse(e.Result);

        itemsFetched.ItemsSource = from item in xmlDoc.Descendants(web + "SampleItem")

找到该项,但在尝试获取Id值时我得到一个null异常。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

xmlns="..."将元素及其所有后代放在命名空间中,因此您需要在访问元素的任何位置使用XNamespace对象web

XDocument xmlDoc = XDocument.Parse(e.Result);
XNamespace web = "http://schemas.datacontract.org/2004/07/WcfRestService1";

itemsFetched.ItemsSource = from item in xmlDoc.Descendants(web + "SampleItem")
                           select new Product()
                                              {
                                                  Id = item.Element(web + "Id").Value,
                                                  StringValue = item.Element(web + "StringValue").Value
                                              };
相关问题