Tôi phải chọn tất cả các nút chứa thuộc tính có tên nhất định.chọn tất cả các nút xml chứa một thuộc tính nhất định
Đây là phương pháp hiện tại, không hoạt động của tôi.
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;
}
tôi cố gắng để chọn tất cả các nút có chứa các thuộc tính với tên được đặt trong tham số phương pháp attributeName
và thêm giá trị biến list
.
Ví dụ:
này gọi phương thức:
List<string> result = RetrieveValuesForAttribute("itemSelectedHandler");
nên trả về một danh sách có chứa chuỗi "OnSelectedRelatedContactChanged"
Đây là tập tin 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>
Hàng đợi khác stions: Nó sẽ là tốt hơn để giải quyết điều này với LINQ?
Giải pháp 1: cảm ơn bạn, 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;
}
Giải pháp 2: cảm ơn bạn, Jon Skeet
public List<string> RetrieveValuesForAttribute(string attributeName)
{
//document is an XDocument
return document.Descendants()
.Attributes(attributeName)
.Select(x => x.Value)
.ToList();
}
Các LINQ to XML Solution trông xa hơn nữa tao nhã với tôi.
Tôi chắc chắn sẽ sử dụng LINQ to XML cho việc này. Thay vào đó, bạn có thể tạo 'document' thành' XDocument' không? –
Vâng tôi có thể, tôi sẽ thử nó với LINQ to XML – Joel