2014-07-10 77 views
0

請考慮下面的代碼:遍歷的XElement和刪除一些標籤

public static XElement ToXElement<T>(this object obj,List<string> JustThisProperties) 
{ 
    using (var memoryStream = new MemoryStream()) 
    { 
     using (TextWriter streamWriter = new StreamWriter(memoryStream)) 
     { 
      var xmlSerializer = new XmlSerializer(typeof(T)); 
      xmlSerializer.Serialize(streamWriter, obj); 
      var xml = XElement.Parse(Encoding.UTF8.GetString(memoryStream.ToArray())); 
      xml.Attributes().Where(a => a.IsNamespaceDeclaration).Remove(); 
      foreach (var item in xml.Elements()) 
      { 
       if (JustThisProperties.Where(o=>o == item.Name.ToString()).Any() == false) 
       { 
        xml.Elements(item.Name.ToString()).Remove(); 
       } 
      } 

      return xml; 
     } 
    } 
} 

和XML:

<Log> 
    <tbl> 
     <ID>21</ID> 
     <MasterID>3</MasterID> 
     <C_2>1</C_2> 
     <C_3>1</C_3> 
     <C_4>1</C_4> 
     <C_5>2000</C_5> 
     <C_6>2</C_6> 
     <C_7>2</C_7> 
     <C_8>2</C_8> 
     <C_9>2</C_9> 
     <C_10>2</C_10> 
    </tb> 
</Log> 

我想序列只是一些性質。例如,當上面產生XML我想刪除除{C_2,C_9,C_10}以外的所有標籤。問題是當它刪除C_2,因爲XML已被更改,它沒有繼續foreach並打破它。我如何從XElement中刪除一些標籤?

感謝

回答