Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
270 views
in Technique[技术] by (71.8m points)

c# - XPath: How to select a node by its attribute?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...