LINQ to XML 是否依赖于顺序?您可以用它对结果进行编号吗?
那么,我的第一个问题是 LINQ to XML 顺序相关吗?
给定 XML(实际文件的简化版本):
<root>
<dl Id='111' Or='true' />
<dl Id='112' Or='false' />
</root>
容器:
public class root
{
public int Position { get; set; }
public int Id { get; set; }
public bool Or { get; set; }
}
读取器代码:
var t = a.DescendantsAndSelf("root").Descendants("dl").Select(b => new root
{
Id = int.Parse(b.Attribute("Id").Value),
Or = bool.Parse(b.Attribute("Or").Value)
});
t
中的根元素是否始终按照从文件中读取的顺序排列?如果没有,有什么办法可以强制执行顺序吗?
第二个问题,有没有办法自动向读取器代码添加一个数字,表明它是否是要从 XML 中读取的第一个、第二个、第三个等根?因此,在此示例中,t
将包含两个值为
- dl.Position = 1、dl.Id = 111、dl.Or = true
- dl.Position = 2、dl.Id = 112 的 元素, dl.Or = false
So, my first question, is LINQ to XML order dependent?
Given the XML (simplified version of the actual file):
<root>
<dl Id='111' Or='true' />
<dl Id='112' Or='false' />
</root>
The container:
public class root
{
public int Position { get; set; }
public int Id { get; set; }
public bool Or { get; set; }
}
The reader code:
var t = a.DescendantsAndSelf("root").Descendants("dl").Select(b => new root
{
Id = int.Parse(b.Attribute("Id").Value),
Or = bool.Parse(b.Attribute("Or").Value)
});
Will the root elements in t
always be in the order they were read out of the file? If not, is there any way to enforce ordering?
The second question, is there any way to automatically add a number to the reader code that says whether it was the first, second, third, etc. root to be read out of the XML? So in this example have it so t
would contain two elements with the values
- dl.Position = 1, dl.Id = 111, dl.Or = true
- dl.Position = 2, dl.Id = 112, dl.Or = false
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,LINQ 是“顺序相关的”。您的对象按照它们在 XML 文件中出现的顺序创建。
要获取位置,请使用包含索引的
Select
版本:Yes, LINQ is "order dependent". Your objects get created in the order in which they appear in the XML file.
To get the position, use the version of
Select
which includes an index: