Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use LINQ on XmlNodeList

Tags:

<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

like image 492
ZHE.ZHAO Avatar asked Dec 01 '15 11:12

ZHE.ZHAO


People also ask

Can I use LINQ on List C#?

Using LINQLINQ features can be used in a C# program by importing the System.

Does LINQ support querying XML datasets?

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.

When should we use LINQ?

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.

Is using LINQ good?

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.


1 Answers

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); 
like image 129
Andrey Korneyev Avatar answered Sep 22 '22 17:09

Andrey Korneyev