简体   繁体   English

想要在xml linq C#中选择所有后代节点

[英]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. 我有下面的xml并尝试选择房间节点内的所有节点问题是房间节点内的节点名称几乎是随机的,因此无法预测。

<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. 创建列表时,在调用此p.Element("attempt").Value == "no"之前,请运行此p.Element("attempt") != null很重要,因此,如果p.Element("attempt")不存在。

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 theListOfValues仅包含在其中找到的值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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