2010-07-07 58 views
0

什么是从这个去最优雅的方式:如何使用LINQ和Lambda巧妙地从XDocument中删除节点?

<?xml version="1.0" encoding="UTF-8"?> 
<foo> 
<bar baz="wii" date="2009-01-01"> 
    <baz value="0" /> 
    <baz value="1" /> 
</bar> 
<bar baz="wii" date="2009-01-02"> 
    <baz value="0" /> 
    <baz value="1" /> 
</bar> 
<bar baz="xbox" date="2009-01-01"> 
    <baz value="0" /> 
    <baz value="1" /> 
</bar> 
<bar baz="xbox" date="2009-01-02"> 
    <baz value="0" /> 
    <baz value="1" /> 
</bar> 
</foo> 

这样:

<foo> 
<bar baz="wii" date="2009-01-02"> 
    <baz value="0" /> 
    <baz value="1" /> 
</bar> 
<bar baz="xbox" date="2009-01-02"> 
    <baz value="0" /> 
    <baz value="1" /> 
</bar> 
</foo> 

理想的情况下,这是采取了“日期”参数的函数。 <foo/>的明显创建和循环添加每个<bar>从表达式返回IEnumerable<XElement>似乎笨重,所以可能有更好的方法。

回答

0

我认为你描述的明显方式实际上是最好的。一个纯粹的LINQ方法可能看起来像

private static XDocument FilterByDate(XDocument doc, DateTime dateTime) 
{ 
    return doc.Root.Elements() 
        .Where(xe => DateTime.Parse(xe.Attribute("date").Value) == dateTime) 
        .Aggregate(new XDocument(new XElement("foo")), 
              (xd, xe) => { xd.Root.Add(xe); return xd; }); 
} 

但我认为聚合部分是不是非常有效。