Question

Question background:

I'm currently trying to access the image link and 'alt' text value from the XML retrieved from a call to the Yahoo news API, as shown below:

XmlNode nodds = xm.SelectSingleNode("/me/p/a/img");

string values = nodds.OuterXml;

The question:

The above string 'values' will give the following XML output:

<img src="http://l.yimg.com/bt/api/res/1.2/nlO7riEkTxPgOISZ8dlWhg--/YXBwaWQ9eW5ld3M7Zmk9ZmlsbDtoPTg2O3E9NzU7dz0xMzA-/http://media.zenfs.com/en_us/News/ap_webfeeds/95a024a0a763a8044a0f6a7067001ac5.jpg" width="130" height="86" alt="Voters hold their identification cards and the chains that held the gate of the polling station closed, as they demand the right to vote during general elections in Bangkok, Thailand, Sunday, Feb. 2, 2014. Around the country, the vast majority of voting stations were open and polling proceeded relatively peacefully, but the risk of violence remained high a day after gun battles in Bangkok left seven people wounded. (AP Photo/Wally Santana)" align="left" title="Voters hold their identification cards and the chains that held the gate of the polling station closed, as they demand the right to vote during general elections in Bangkok, Thailand, Sunday, Feb. 2, 2014. Around the country, the vast majority of voting stations were open and polling proceeded relatively peacefully, but the risk of violence remained high a day after gun battles in Bangkok left seven people wounded. (AP Photo/Wally Santana)" border="0" />

What is the correct way to split the above string up so that I can access:

  1. The image link

  2. The alt text value

Was it helpful?

Solution

You should take advantage of the Attributes collection (represented by XmlAttributeCollection) which is a part of your XmlNode:

var alt = nodds.Attributes["alt"].Value;
var src = nodds.Attributes["src"].Value;

To make it error-proof you could extend it to something like this:

string altValue; 
var altAttribute = nodds.Attributes["alt"];
if(altAttribute != null) 
{
    altValue = nodds.Attributes["alt"].Value; 
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top