Extracting text from XML Element with attributes
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 t开发者_StackOverflowhe second link? (the link for the large image, since is the only one that I need)?
Thank you in advance.
If you don't trust the order and you want to use the size attribute do:
x.SelectSingleNode("image[@size='large']")
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
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.
精彩评论