我想知道如何使用XML文档在1个select语句中选择多个对象初始值设定项。我想避免在同一个文件上进行多次迭代。
XML结构如下所示:
<root>
<doc name="test.doc">
<version lang="nl">
</version>
<version lang="fr">
</version>
</doc>
<doc name="test2.doc">
<version lang="nl">
<title>Document over ons</title>
</version>
<version lang="fr">
<title>Document de nous</title>
</version>
</doc>
</root>
1个元素的LINQ语句如下所示:
var docs = select e from xmlDoc.Descendants("doc")
select new docEntry()
{
Name = (string)e.Attribute("name"),
Title = (string)element.Elements("version").Where(d => (string)d.Attribute("language_code") == "nl").First().Element("title")
}
现在我想在1中选择法语版本,伪代码如下:
var docs = select e from xmlDoc.Descendants("doc")
select new docEntry()
{
Name = (string)e.Attribute("name"),
Title = (string)element.Elements("version").Where(d => (string)d.Attribute("language_code") == "nl").First().Element("title")
},
select new docEntry()
{
Name = (string)e.Attribute("name"),
Title = (string)element.Elements("version").Where(d => (string)d.Attribute("language_code") == "fr").First().Element("title")
}
关于如何在1中完成此任务的任何想法?我知道我可以通过XML进行两次往返,但那会很愚蠢,不是吗?
答案 0 :(得分:4)
var docs = from e in xmlDoc.Descendants("doc")
select new
{
NL = new docEntry
{
Name = e.Attribute("name").Value,
Title = e.Elements("version").Where(d => d.Attribute("language_code").Value == "nl").First().Element("title").Value
},
FR = new docEntry
{
Name = e.Attribute("name").Value,
Title = e.Elements("version").Where(d => d.Attribute("language_code").Value == "fr").First().Element("title").Value
}
};
另一个略有不同的选择:
var docs = from e in from xmlDoc.Descendants("doc")
select new[]
{
new docEntry
{
Name = e.Attribute("name").Value,
Title = e.Elements("version").Where(d => d.Attribute("language_code").Value == "nl").First().Element("title").Value
},
new docEntry
{
Name = e.Attribute("name").Value,
Title = e.Elements("version").Where(d => d.Attribute("language_code").Value == "fr").First().Element("title").Value
}
};