选择所有包含某个属性的 xml 节点 [英] select all xml nodes which contain a certain attribute
问题描述
我必须选择包含具有特定名称的属性的所有节点.
I have to select all nodes which contain an attribute with a certain name.
这是我目前的方法,不可行.
This is my current, not working approach.
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
.
I try to select all nodes which contain the attribute with the name given in the method parameter attributeName
and add the value the variable list
.
示例:
这个方法调用:
List<string> result = RetrieveValuesForAttribute("itemSelectedHandler");
应该返回一个包含字符串OnSelectedRelatedContactChanged"的列表
Should return an list which contains the string "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>
其他问题:用 LINQ 解决这个问题会更好吗?
Further questions: Would it be better to solve this with 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 to XML 解决方案在我看来要优雅得多.
The LINQ to XML Solution looks far more elegant to me.
推荐答案
如果您可以为此使用 LINQ to XML,那将是微不足道的:
If you could use LINQ to XML for this, it would be utterly trivial:
// 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();
}
这篇关于选择所有包含某个属性的 xml 节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!