选择包含特定属性的所有xml节点

Joe*_*oel 7 c# xml xpath

我必须选择包含具有特定名称的属性的所有节点.

这是我目前的工作方法.

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;
} 
Run Code Online (Sandbox Code Playgroud)

我尝试选择包含具有method参数中给出的名称的属性的所有节点,attributeName并将值添加到变量中list.

例:

这个方法调用:

List<string> result = RetrieveValuesForAttribute("itemSelectedHandler");
Run Code Online (Sandbox Code Playgroud)

应返回包含字符串"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>
Run Code Online (Sandbox Code Playgroud)

进一步的问题:用LINQ解决这个问题会更好吗?

解决方案1:谢谢你,嗯

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;
}
Run Code Online (Sandbox Code Playgroud)

解决方案2:谢谢Jon Skeet

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

LINQ to XML解决方案对我来说看起来更优雅.

Jon*_*eet 9

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


ywm*_*ywm 5

您正在寻找的 XPath 应该是

"//*[@" + attributeName + "]"
Run Code Online (Sandbox Code Playgroud)

您原来的 XPath 正在做的是寻找具有Name值的属性的所有元素attributeName

这将查找任何具有 attributeName 属性的元素

//*[@title]
Run Code Online (Sandbox Code Playgroud)

将返回列元素