【问题标题】:want to select all the descendant nodes in xml linq c#想要选择xml linq c#中的所有后代节点
【发布时间】:2017-07-30 16:18:36
【问题描述】:

我有以下 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>

我已经尝试过了,但它会将所有后代节点房间信息作为一个字符串返回,我希望该信息用字符串分隔

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

【问题讨论】:

  • i.Element("attempt").Value
  • i.Element("attempt").Value 会在 xml 中找不到元素(null)时返回错误,而(string)i.Element("attempt") 不会返回错误
  • 你需要检查元素是否为空
  • 仍然无法正常工作。它返回 11nononono09/03/20174.23 作为一个字符串,我希望至少用逗号分隔它们 1,1,no,no,no,no,09/03/2017,4.23 或每个值的不同字符串

标签: c# asp.net xml


【解决方案1】:

在创建列表时,在调用此 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

theListOfValues 仅包含在其中找到的值

【讨论】:

  • 随时。我将添加一些 cmets 和 string.join()
猜你喜欢
  • 1970-01-01
  • 2017-05-12
  • 1970-01-01
  • 2020-08-28
  • 1970-01-01
  • 2013-11-07
  • 1970-01-01
  • 2016-12-19
  • 1970-01-01
相关资源
最近更新 更多