简体   繁体   中英

want to select all the descendant nodes in xml linq c#

I have following xml and trying to select all nodes inside the room node problem is that names of nodes inside the room node are almost random, therefore impossible to predict.

<room>
<info>1</info>
<something_here>1</something_here>
<something_else_here>no</something_else_here>
<something_else_here>no</something_else_here>
<something_else>no</something_else>
<attempt>no</attempt>
<date>09/03/2017</date>
<room_name>4.23</room_name>

I have tried this, but it´s returning all the descendant node room info as one string, and I want to that info to be separated by strings

tabela = xdoc.Descendants("room")
            .Where(i => (string)i.Element("attempt") == Convert.ToString("no"))
           .Select(element => element.Value).ToList();

When creating the list, it's important to run this p.Element("attempt") != null before you call this p.Element("attempt").Value == "no" so it does not throw an error if p.Element("attempt") does not exist.

XDocument thedoc = XDocument.Load(@"M:\StackOverflowQuestionsAndAnswers\XML_42699433\XML_42699433\file.xml");
List<string> theListOfValues = thedoc.Descendants("room")
.Where(p => p.Element("attempt") != null && p.Element("attempt").Value == "no")
.Elements()
.Select(p => p.Value).ToList();
string asLongString = string.Join(",", theListOfValues);
//make it the string you seem to be after

The theListOfValues contains only the values found within

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM