10

I have an XML that goes like this:

<?xml version="1.0" encoding="utf-8" ?>
<colors>
  <color index = "0">#FF0000</color>
  <color index = "1">#FF0200</color>
  <color index = "2">#FF0300</color>
  <color index = "3">#FF0500</color>
  [..]

I'm trying to select a node by its index:

XmlDocument ColorTable = new XmlDocument();
ColorTable.Load(HttpContext.Current.Server.MapPath("~/App_Data/ColorTable.xml"));
int percentage = 2;
string xpath = string.Format(@"//color[index={0}]", percentage.ToString());
//string xpath = string.Format(@"//color[index=""{0}""]", percentage.ToString());
//string xpath = string.Format(@"//color[index='{0}']", percentage.ToString());
var r = ColorTable.SelectSingleNode(xpath).Value;

I tried also the commented versions, but it does not return any result. Any suggestion?

pistacchio
  • 56,889
  • 107
  • 278
  • 420

2 Answers2

21

Use //color[@index='{0}'] instead. The @ sign means "attribute".

I note that you're using a verbatim string literal by the way - the @ sign at the start of the string. There's no need in this case - you don't have any backslashes in the string, and it's not multi-line. You also don't need to explicitly call ToString on percentage - it will be converted automatically.

string xpath = string.Format("//color[@index='{0}']", percentage);
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Why does the 0 have to be enclosed in curly braces? I use XPATH inside Novell IDM, and @index=0 would have been sufficient there. What do the curly braces indicate? – geoffc Jul 01 '09 at 13:45
  • 3
    its not part of the xpath, it's part of the String.Format, it will be replaces with the 1st param (ie percentage) – Shay Erlichmen Jul 01 '09 at 13:49
9

BTW, for those of us who doesn't speak native XPath, there are many online XPath "playgrounds" that allow you to write XML and XPath expression and see the results online.

Whenever I found myself in a "XPath hell" I usually go to those playgrounds and try various combination till I get my (needed) results, for some reason it works faster than writing C#/Python test program or even running those bloated so called XML editors.

Shay Erlichmen
  • 31,691
  • 7
  • 68
  • 87