tags:

views:

31

answers:

3

I have a xml file like this one:

<root>
<image size = "small">www.linktosmallimage.jpg</image>
<image size = "large">www.linktolargeimage.jpg</image>
</root>

Im extracting the first link in this way:

foreach (XmlElement x in xmlSource.SelectNodes("/root"))
            {
             string s = x.SelectSingleNode("image").InnerText;
            }

The question is: How do I get the second link? (the link for the large image, since is the only one that I need)?

Thank you in advance.

A: 

x.SelectSingleNode("image[2]")

Strangely, XPath arrays begin on 1 rather than [0].

Lots of information on XPath here: http://www.w3schools.com/xpath/default.asp

By the way, you should look into System.Xml.Linq -- the syntax is bulkier, but it's a bit more robust.

Rei Miyasaka
+1  A: 
string s;
foreach(XmlElement x in xmlSource.SelectNodes("/root/image"))
{
  s = x.InnerText;
}

if you always want the last one.
Or you can do:

        XmlNode y = xmlSource.SelectSingleNode("/root/image[@size=\"large\"]");
        string s = y.InnerText;

in which case the order of the elements doesn't matter, you will always get the element with the attribute size = large assuming there is only one such element. If the assumption holds this is the better approach. Here are some good XPath Examples

Steve Ellinger
+1  A: 

If you don't trust the order and you want to use the size attribute do:

x.SelectSingleNode("image[@size='large']") 
gcores
Perfect! Thanks a lot!
Lenhador de Ygddrasil