我有以下xml结构
<userlist>
<user Name="something">
<function name="funcname">
<picture name="pictname">
<curve name="curvename">
<name>NAME</name>
...
</curve>
</picture>
</function>
<function name="function2">
...
</function>
</user>
它继续一点。我编写了一个函数来提取“函数”标签,并使用简化为的代码将它们放置在对象中:
from function in xmlDoc.Descendants("function")
select new FUNCTIONOBJECT {
do all the rest...
}.toList<FUNCTIONOBJECT>();
我现在正试图做到这一点,以便我只过滤给定用户的功能。所以给出了用户的名称属性。谁能告诉我如何使用 LINQ 进行这项工作?我的尝试是:
from user in xmlDoc.Descendants("user")
where user.Attribute("Name").Value == givenusername
select {
var functions =
from function in user.Descendants("function")
select new FUNCTIONOBJECT {
... more stuff
}.toList<FUNCTIONOBJECT>();
但这是错误的并且不起作用。所有的帮助都是好的。我对 c# 还是很陌生,仍然试图用 LINQ 进行 xml 解析。
编辑:我所拥有的更新版本仍然无法正常工作:
XDocument xmlDoc = XDocument.Load(path);
var functionlist =
(from user in xmlDoc.Descendants("user")
where user.Attribute("Name").Value == username
select(
(from function in user.Descendants("function")
select new Function
{
name = function.Attribute("name").Value,
pictures =
(from picture in function.Descendants("picture")
select new Picture
{
name = picture.Attribute("name").Value,
layout = picture.Element("layout").Value,
curves =
(from curve in picture.Descendants("curve")
select new Curve
{
name = curve.Attribute("name").Value,
section = curve.Element("section").Value,
run = curve.Element("run").Value,
folder = curve.Element("folder").Value,
drivingpoint = curve.Element("drivingpoint").Value,
display = int.Parse(curve.Element("display").Value),
points =
(from point in curve.Descendants("point")
select new Point
{
id = point.Element("id").Value != null ? point.Element("id").Value : string.Empty,
direction = point.Element("direction").Value != null ? point.Element("direction").Value : string.Empty,
}).ToList<Point>(),
}).ToList<Curve>(),
}).ToList<Picture>(),
}).ToList<Function>(),
).toList();
}