0

我正在制作基于 web 服务的 windows phone 8 应用程序。这是我的 xml 代码:

- <response>
      <timestamp>2013-10-31T08:30:56Z</timestamp> 
      <resultsOffset>0</resultsOffset> 
      <status>success</status> 
      <resultsLimit>8</resultsLimit> 
      <resultsCount>38</resultsCount> 
    - <headlines>
    - <headlinesItem>
      <headline>City edge past Toon</headline> 
      <keywords /> 
      <lastModified>2013-10-30T23:45:22Z</lastModified> 
      <audio /> 
      <premium>false</premium> 
    + <links>
    - <api>
    - <news>
      <href>http://api.espn.com/v1/sports/news/1600444?region=GB</href> 
      </news>
      </api>
    - <web>
      <href>http://espnfc.com/uk/en/report/381799/city-edge-toon?ex_cid=espnapi_public</href> 
      </web>
    - <mobile>
      <href>http://m.espn.go.com/soccer/gamecast?gameId=381799&lang=EN&ex_cid=espnapi_public</href> 
      </mobile>
      </links>
      <type>snReport</type> 
      <related /> 
      <id>1600444</id> 
      <story>Alvardo Negredo and Edin Dzeko struck in extra-time to book Manchester City's place in the last eight of the Capital One Cup, while Costel Pantilimon kept a clean sheet in the 2-0 win to keep the pressure on Joe Hart. </story> 
      <linkText>Newcastle 0-2 Man City</linkText> 
    - <images>
    - <imagesItem>
      <height>360</height> 
      <alt>Man City celebrate after Edin Dzeko scored their second extra-time goal at Newcastle.</alt> 
      <width>640</width> 
      <name>Man City celeb Edin Dzeko goal v nufc 20131030 [640x360]</name> 
      <caption>Man City celebrate after Edin Dzeko scored their second extra-time goal at Newcastle.</caption> 
      <type>inline</type> 
      <url>http://espnfc.com/design05/images/2013/1030/mancitycelebedindzekogoalvnufc20131030_640x360.jpg</url> 
      </imagesItem>
      </images>

后面的代码:

 myData = XDocument.Parse(e.Result, LoadOptions.None);
 var data = myData.Descendants("headlines").FirstOrDefault();
 var data1 = from query in myData.Descendants("headlinesItem")
             select new UpdataNews
             {
                 News = (string)query.Element("headline").Value,
                 Desc = (string)query.Element("description"),
                 Newsurl = (string)query.Element("links").Element("mobile").Element("href"),
                 Imageurl = (string)query.Element("images").Element("imagesItem").Element("url").Value,
            };
lstShow.ItemsSource = data1;

我正在尝试从 xml 标记中获取值并将它们分配给 News、Desc 等。除了 Imageurl 之外一切正常,它显示 NullException。我为 Imageurl 尝试了相同的方法,我不知道出了什么问题。

4

1 回答 1

1

您正在寻找:

  Imageurl=(string)query.Element("images").Element("imagesItem").Element("url").Value

但是“imagesItem”不是“images”的子元素,它是兄弟元素。

已编辑

好的,这可能是因为其中一个路径缺少 <"url"> 元素。所以,考虑到这一点。

Imageurl=query.Element("images").Element("imagesItem").Element("url") != null ? Imageurl=(string)query.Element("images").Element("imagesItem").Element("url").Value : "no image",
于 2013-10-31T10:04:51.750 回答