选择包含特定属性的所有xml节点
我必须选择包含具有特定名称的属性的所有节点。
这是我目前的工作方法。
public List RetrieveValuesForAttribute(string attributeName) { var list = new List(); string xpath = "//*[@Name='" + attributeName + "']"; XmlNodeList xmlNodeList = document.SelectNodes(xpath); foreach (XmlNode xmlNode in xmlNodeList) { list.Add(xmlNode.Attributes[attributeName].InnerText); } return list; }
我尝试选择包含具有方法参数attributeName
给出的名称的属性的所有节点,并将值添加到变量list
。
例:
这个方法调用:
List result = RetrieveValuesForAttribute("itemSelectedHandler");
应返回包含字符串“OnSelectedRelatedContactChanged”的列表
这是xml文件:
0 false 0 false 0 true
进一步的问题:用LINQ解决这个问题会更好吗?
解决方案1:谢谢你,嗯
public List RetrieveValuesForAttribute(string attributeName) { var list = new List(); string xpath = @"//*[@" + attributeName + "]"; XmlNodeList xmlNodeList = document.SelectNodes(xpath); foreach (XmlNode xmlNode in xmlNodeList) { list.Add(xmlNode.Attributes[attributeName].InnerText); } return list; }
解决方案2:谢谢Jon Skeet
public List RetrieveValuesForAttribute(string attributeName) { //document is an XDocument return document.Descendants() .Attributes(attributeName) .Select(x => x.Value) .ToList(); }
LINQ to XML解决方案对我来说看起来更优雅。
如果您可以使用LINQ to XML,那将是完全无关紧要的:
// Note that there's an implicit conversion from string to XName, // but this would let you specify a namespaced version if you want. public List RetrieveValuesForAttribute(XName attributeName) { // Assume document is an XDocument return document.Descendants() .Attributes(attributeName) .Select(x => x.Value) .ToList(); }
你正在寻找的XPath应该是
"//*[@" + attributeName + "]"
原始XPath正在做的是查找具有值attributeName
的Name
属性的所有元素
这将查找具有attributeName属性的任何元素
//*[@title]
将返回列元素
我不确定C#语法,但我认为xpath vlaue是错误的。 请尝试:“// * [@ itemSelectedHandler]”。 c#应该怎么做
string xpath = "//*[@" + attributeName + "]";