DooDoo
DooDoo

Reputation: 13467

Loop through XElement and remove some tags

please consider this code:

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;
        }
    }
}

and 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>

I want to serialize just some properties. For example when above XML generated I want to remove all tags except {C_2,C_9,C_10}. The problem is when it remove C_2 because XML has been change it did not continue the foreach and break it. How I can remove some tags from an XElement?

thanks

Upvotes: 0

Views: 598

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1501606

You can use the Remove extension method on IEnumerable<T> where T : XNode:

xml.Elements()
   .Where(item => !JustThisProperties.Contains(item.Name.ToString()))
   .Remove();

(You might want to make JustThisProperties an IEnumerable<XName>, which would let you get rid of the ToString() call.)

Upvotes: 2

Related Questions