如何在xml文件中查找节点的特定值

时间:2013-10-31 09:50:24

标签: c# xml windows-phone

我正在基于webservices制作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尝试了相同的方法,我不知道出了什么问题。

1 个答案:

答案 0 :(得分:1)

您正在寻找:

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

但是“imagesItem”不是“图像”的子元素,它是一个兄弟。

被修改

好的,可能是因为&lt;“url”&gt;其中一个路径缺少元素。所以,考虑到这一点。

Imageurl=query.Element("images").Element("imagesItem").Element("url") != null ? Imageurl=(string)query.Element("images").Element("imagesItem").Element("url").Value : "no image",