2013-04-11 135 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 + "]"; 
相關問題