[英]How can I select all subnodes of a node, and not all descendats?
我有以下XML:
<...>
<...>
<tabular>
<time from="2014-05-22T10:00:00" to="2014-05-22T12:00:00" period="1">
<symbol number="3" numberEx="3" var="03d" />
<precipitation value="0" />
<windDirection deg="191.8" code="SSW" />
<windSpeed mps="1.3" />
<temperature unit="celsius" value="16" />
<pressure unit="hPa" value="1010.6" />
</time>
<time from="2014-05-22T10:00:00" to="2014-05-22T12:00:00" period="1">
<symbol number="3" numberEx="3" var="03d" />
<precipitation value="0" />
<windDirection deg="191.8" code="SSW" />
<windSpeed mps="1.3" />
<temperature unit="celsius" value="16" />
<pressure unit="hPa" value="1010.6" />
</time>
<time from="2014-05-22T10:00:00" to="2014-05-22T12:00:00" period="1">
<symbol number="3" numberEx="3" var="03d" />
<precipitation value="0" />
<windDirection deg="191.8" code="SSW" />
<windSpeed mps="1.3" />
<temperature unit="celsius" value="16" />
<pressure unit="hPa" value="1010.6" />
</time>
我已经使用LINQ来获取表格列表:
var tabular = doc.Root.Descendants("tabular").ToList();
表格计数现在为1。我想要的是表格列表的子项列表。 我尝试了额外的后代:
var tabular = doc.Root.Descendants("tabular").Descendants().ToList();
但这会返回列表的每个后代的列表,从而产生一个列表,其中时间,符号,降水量等在列表中。 如何获得列表中包含表格时间节点的列表?
我需要所有时间节点的列表,因此可以将其序列化为一个对象并访问值
如果只想获取tabular
直接子Elements
,请使用Elements
而不是Descendants
var tabular = doc.Root.Descendants("tabular").Elements().ToList();
更新:提示将时间元素解析为对象
var times =
from t in xdoc.Descendants("tabular").Elements()
let symbol = t.Element("symbol")
let temperature = t.Element("temperature")
select new
{
From = (DateTime)t.Attribute("from"),
To = (DateTime)t.Attribute("to"),
Period = (int)t.Attribute("period"),
Symbol = new
{
Number = (int)symbol.Attribute("number"),
NumberEx = (int)symbol.Attribute("numberEx"),
Var = (string)symbol.Attribute("var")
},
Precipitation = (int)t.Element("precipitation").Attribute("value"),
WindSpeed = (double)t.Element("windSpeed").Attribute("mps"),
Temperature = new
{
Unit = (string)temperature.Attribute("unit"),
Value = (string)temperature.Attribute("value")
}
};
输出:
[
{
From: "2014-05-22T10:00:00",
To: "2014-05-22T12:00:00",
Period: 1,
Symbol: { Number: 3, NumberEx: 3, Var: "03d" },
Precipitation: 0,
WindSpeed: 1.3,
Temperature: { Unit: "celsius", Value: "16" }
},
// ...
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.