<X version="1.0"> <Y id="abc" abv="a"/> <Y id="edf" abv="e"/> </X>
I want to select the node whose id is "abc", and return its abv "a".
XmlDocument doc = new XmlDocument(); doc.Load(filePath); XmlNodeList list = doc.SelectNodes("X/Y"); var node = list.Cast<XmlNode>().Where(node => node["id"].InnerText == "abc") .Select(x=>x["abv"].InnerText);
But it does't work, node["id"].InnerText is always "". Can you point out where is a problem?
Thanks a lot
Using LINQLINQ features can be used in a C# program by importing the System.
The most important advantage of LINQ to XML is its integration with Language-Integrated Query (LINQ). This integration enables you to write queries on the in-memory XML document to retrieve collections of elements and attributes.
LINQ in C# is used to work with data access from sources such as objects, data sets, SQL Server, and XML. LINQ stands for Language Integrated Query. LINQ is a data querying API with SQL like query syntaxes. LINQ provides functions to query cached data from all kinds of data sources.
The LINQ architecture is good - but some may prefer to read source code that does not use the LINQ SQL-like syntax. So if you're strict on readability, you may want not to use that syntax. Readability is not that big issue.
Aside from the fact what your code snippet wouldn't be compiled because of non-unique node
variable (first outside of linq query and second in "where" method lambda), you have also missed Attributes
in your query.
It should be something like
var node = list.Cast<XmlNode>() .Where(n => n.Attributes["id"].InnerText == "abc") .Select(x => x.Attributes["abv"].InnerText);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With