Search XML file for nodes with specific attribute value in .NET 2

五迷三道 提交于 2019-12-17 19:27:36

问题


I found answers for searching XML nodes using LINQ, but I am limited to C# with .NET 2.

I want to open a single XML file (~50Kb, all simple text) and search for all <Tool> nodes with attribute name having a specific value.

It seems like XmlDocument.SelectNodes() might be what I'm looking for, but I don't know XPath. Is this the right way and if so what would code look like?


回答1:


You can use XPath in XmlDocument.SelectNodes such as: SelectNodes("//ElementName[@AttributeName='AttributeValue']")

Xml Sample:

<root>
    <element name="value1" />
    <element name="value2" />
    <element name="value1" />
</root>

C# Sample:

XmlDocument xDoc = new XmlDocument();
// Load Xml

XmlNodeList nodes = xDoc.SelectNodes("//element[@name='value1']");
// nodes.Count == 2

Here you can find some additional XPath samples




回答2:


think you could do something like that (well, rustic, but you've got the idea), using GetElementsByTagName

var myDocument = new XmlDocument();
myDocument.Load(<pathToYourFile>);
var nodes = myDocument.GetElementsByTagName("Tool");
var resultNodes = new List<XmlNode>();
foreach (XmlNode node in nodes)
{
    if (node.Attributes != null && node.Attributes["name"] != null && node.Attributes["name"].Value == "asdf")
    resultNodes.Add(node);
}


来源:https://stackoverflow.com/questions/14501038/search-xml-file-for-nodes-with-specific-attribute-value-in-net-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!