我有以下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();
但是返回表格的每个后代的列表,导致列表中的时间,符号,降水等等。如何获得列表中包含表格的时间节点的列表?
我想要一个所有时间节点的列表,所以我可以将它序列化为一个对象并访问值
答案 0 :(得分:4)
如果您只想获得Elements
的直接子女
Descendants
代替tabular
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" }
},
// ...
]