我与具有结构(部分)现有的XML文档的工作,像这样:的LINQ to XML可选元素查询
<Group>
<Entry>
<Name> Bob </Name>
<ID> 1 </ID>
</Entry>
<Entry>
<Name> Larry </Name>
</Entry>
</Group>
我使用LINQ to XML查询的XDocument检索所有这些条目如下:
var items = from g in xDocument.Root.Descendants("Group").Elements("Entry")
select new
{
name = (string)g.element("Name").Value,
id = g.Elements("ID").Count() > 0 ? (string)g.Element("ID").Value : "none"
};
“ID”元素并不总是存在,所以我的解决方案是上面的Count()爵士乐。但我想知道是否有人有更好的方法来做到这一点。我仍然对这个新东西感到满意,我怀疑可能有更好的方法来做到这一点,而不是我目前正在做的事情。
有没有更好的/更喜欢的方式来做我想要的?
非常整齐和整洁 – 2008-11-10 15:58:03
我喜欢它 - 谢谢。 – itsmatt 2008-11-10 16:08:46