Search code examples
c#linq-to-xmlxml-nil

Cleans the Xml element with the attribut "nil=true" - Create linq version?


I'm trying to cleans the Xml element with the attribut "nil=true" inside a document. I come up with this algo but I don't like how it's look.

Do anyone know a linq version of this algo?

    /// <summary>
    /// Cleans the Xml element with the attribut "nil=true".
    /// </summary>
    /// <param name="value">The value.</param>
    public static void CleanNil(this XElement value)
    {
        List<XElement> toDelete = new List<XElement>();

        foreach (var element in value.DescendantsAndSelf())
        {
            if (element != null)
            {
                bool blnDeleteIt = false;
                foreach (var attribut in element.Attributes())
                {
                    if (attribut.Name.LocalName == "nil" && attribut.Value == "true")
                    {
                        blnDeleteIt = true;
                    }
                }
                if (blnDeleteIt)
                {
                    toDelete.Add(element);
                }
            }
        }

        while (toDelete.Count > 0)
        {
            toDelete[0].Remove();
            toDelete.RemoveAt(0);
        }
    }

Solution

  • What's the namespace of the nil attribute? Put that inside { } like this:

    public static void CleanNil(this XElement value)
    {
        value.Descendants().Where(x=> (bool?)x.Attribute("{http://www.w3.org/2001/XMLSchema-instance}nil") == true).Remove();
    }