2010-07-07 60 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; }); 
} 

但我認爲聚合部分是不是非常有效。