SelectingAllxmlNodesContainingaSpecificAttribute我必须选择包含具有特定名称的属性的所有节点。这是我目前的工作方法。publicListRetrieveValuesForAttribute(stringattributeName){varlist=newList();stringxpath="//*[@Name='"+attributeName+"']";XmlNodeListxmlNodeList=document.SelectNodes(xpath);foreach(XmlNodexmlNodeinxmlNodeList){list.Add(xmlNode.Attributes[attributeName].InnerText);}返回列表;我尝试选择所有包含属性的节点,该属性的名称由方法参数attributeName给出,并将该值添加到变量列表。示例:此方法调用:Listresult=RetrieveValuesForAttribute("itemSelectedHandler");应该返回一个包含字符串“OnSelectedRelatedContactChanged”的列表这是xml文件:0false0false0true进一步的问题:用LINQ解决这个问题会更好吗?解决方案1:谢谢,嗯publicListRetrieveValuesForAttribute(stringattributeName){varlist=newList();stringxpath=@"//*[@"+attributeName+"]";XmlNodeListxmlNodeList=document.SelectNodes(xpath);foreach(XmlNodexmlNodeinxmlNodeList){list.Add(xmlNode.Attributes[attributeName].InnerText);}返回列表;}解决方案2:谢谢JonSkeetpublicListRetrieveValuesForAttribute(stringattributeName){//document是一个XDocumentLINQtoXML解决方案对我来说看起来更优雅。如果您可以使用LINQtoXML,那将是完全无关紧要的://请注意,存在从字符串到XName的隐式转换,//但如果需要,这将允许您指定命名空间版本。publicListRetrieveValuesForAttribute(XNameattributeName){//假设文档是一个XDocumentreturndocument.Descendants().Attributes(attributeName).Select(x=>x.Value).ToList();您正在寻找的XPath应该是"//*[@"+attributeName+"]"原始XPath正在做的是查找所有具有Name属性且值为attributeName的元素这将找到具有属性的任何元素ofattributeName//*[@title]将返回列元素我不确定C#语法,但我认为xpath值是错误的。尝试:“//*[@itemSelectedHandler]”。c#应该做什么?以上就是C#学习教程:选择所有包含特定属性的xml节点共享的内容。如果对大家有用,需要详细了解C#学习教程,希望大家多多关注——stringxpath="//*[@"+attributeName+"]";本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
