如何在C#中按以…开头的属性选择节点

我有这个xml文档,我希望按’/ employees /’开头的属性选择节点。

Employee 1 Robert
Employee 2 Jennifer

所以在C#中,我会做这样的事情:

 parentNode.SelectNodes("//table/tr/th/a[@href='/employees/.....']") 

这可能与C#有关吗?

谢谢!

简单的starts-withfunction可以满足您的需求:

 parentNode.SelectNodes("//table/tr/td/a[starts-with(@href, '/employees/')]") 

使用纯LINQ你可以做这样的事情

 var doc = XDocument.Parse("YOUR_XML_STRING"); var anchors = from e in doc. Descendants("a") where e.Attribute("href").Value.StartsWith("/employee/") select e; 

//现在你可以通过组合.Parent.Parent来看到任何节点…..

那么,这样的事情呢?

 var xml = @"
Employee 1 Robert
Employee 2 Jennifer
"; var doc = new XmlDocument(); doc.LoadXml(xml); var employees = doc.SelectNodes("/table/tr/td/a[starts-with(@href, '/employees/')]"); DoWhatever(employees);

当然,您可以将XML加载到XDocument实例中,并使用XPathSelectElements方法使用表达式进行搜索。