2013-04-11 132 views
6

我必须选择包含具有某个特定名称的属性的所有节点。选择包含特定属性的所有xml节点

这是我目前的工作方法。

public List<string> RetrieveValuesForAttribute(string attributeName) 
{ 
    var list = new List<string>(); 

    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<string> result = RetrieveValuesForAttribute("itemSelectedHandler"); 

应该返回包含字符串的列表 “OnSelectedRelatedContactChanged”

这是XML文件:

<GroupBoxWrapper id="gbRelatedContacts" text="Related Contacts"> 
    <TabIndex>0</TabIndex> 
    <TabStop>false</TabStop> 
    <PanelWrapper id="pnlRelatedContactsView" width="1350"> 
    <TabIndex>0</TabIndex> 
    <TabStop>false</TabStop> 
    <ListViewWrapper id="lvRelatedContacts" itemSelectedHandler="OnSelectedRelatedContactChanged" itemDoubleClickHandler="OnRelatedContactDoubleClick"> 
     <TabIndex>0</TabIndex> 
     <TabStop>true</TabStop> 
     <ListViewColumns> 
     <Column title="Name" mapNode="Contact\Name" /> 
     <Column title="Lastname" mapNode="Contact\Lastname" /> 
     </ListViewColumns> 
    </ListViewWrapper> 
    </PanelWrapper> 
</GroupBoxWrapper> 

更多que提问: 用LINQ解决这个问题会更好吗?

解决方案1:谢谢你,YWM

public List<string> RetrieveValuesForAttribute(string attributeName) 
{ 
    var list = new List<string>(); 

    string xpath = @"//*[@" + attributeName + "]"; 
    XmlNodeList xmlNodeList = document.SelectNodes(xpath); 

    foreach (XmlNode xmlNode in xmlNodeList) 
    { 
     list.Add(xmlNode.Attributes[attributeName].InnerText); 
    } 

    return list; 
} 

解决方案2:谢谢你,乔恩斯基特

public List<string> RetrieveValuesForAttribute(string attributeName) 
{ 
    //document is an XDocument 
    return document.Descendants() 
        .Attributes(attributeName) 
        .Select(x => x.Value) 
        .ToList(); 
} 

的LINQ到XML解决方案看起来更优雅的给我。

+1

我肯定会使用LINQ到XML为此。你可以用'document'作为'XDocument'吗? – 2013-04-11 09:55:33

+0

是的,我可以,我会尝试用LINQ到XML – Joel 2013-04-11 09:58:11

回答

8

如果你可以使用LINQ到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<string> RetrieveValuesForAttribute(XName attributeName) 
{ 
    // Assume document is an XDocument 
    return document.Descendants() 
        .Attributes(attributeName) 
        .Select(x => x.Value) 
        .ToList(); 
} 
4

你正在寻找的XPath是

"//*[@" + attributeName + "]" 

你的初始的XPath所做的就是寻找对于具有Name属性且值为attributeName

的所有元素这将查找具有attr属性的任何元素ibuteName

//*[@title] 

将返回列元素

+0

谢谢你的解决方案,它工作正常。但我更喜欢LINQ to XML方法。 – Joel 2013-04-11 10:09:18

1

林不知道有关C#语法,但我认为的XPath vlaue是错误的。 请尝试:“// * [@ itemSelectedHandler]”。 什么应该在c#

string xpath = "//*[@" + attributeName + "]"; 
相关问题