Search code examples
c#xmlfor-loopremovechildparent-node

Deleting a node from an xmlNodeList


here is my code

    public bool limitOutput()
    {
        double lowerLeftPointX = m_mapControl.CurrentExtent.LowerLeftPoint.X;
        double lowerLeftPointY = m_mapControl.CurrentExtent.LowerLeftPoint.Y;
        double upperRightPointX = m_mapControl.CurrentExtent.UpperRightPoint.X;
        double upperRightPointY = m_mapControl.CurrentExtent.UpperRightPoint.Y;

        for(int i = locationElements.Count - 1; i >= 0; i--)
        {
            if (Double.Parse(locationElements[i]["GEOMETRY_X"].InnerText) < lowerLeftPointX || Double.Parse(locationElements[i]["GEOMETRY_X"].InnerText) > upperRightPointX || Double.Parse(locationElements[i]["GEOMETRY_Y"].InnerText) < lowerLeftPointY || Double.Parse(locationElements[i]["GEOMETRY_Y"].InnerText) > upperRightPointY)
            {
                locationElements[i].ParentNode.RemoveChild(locationElements[i]);
            }
        }

        if (locationElements.Count == 0)
        {
            PearMessageBox.Show(PearMessageBox.mBoxType.simpleNotification, "No results found in specified area");
            return false;
        }
        return true;


    }

I am trying to delete all the nodes which are not within the boundary I have set. The delete line is executed but does not actually delete as when I count locationElements it is still the same value before the method is executed.

Any ideas what is wrong with the code


Solution

  • The problem is due to the fact that RemoveChild() removed the element from the source XmlDocument, but not from the pre-populated XmlNodeList. So you need to execute again the code that was used to pre-populate locationElements variable, something like this :

    //assume that GetLocationElements() is a method...
    //...containing the same logic you used to populate locationElements variable
    var updatedLocationElements = GetLocationElements();
    if (updatedLocationElements.Count == 0)
    {
        PearMessageBox.Show(PearMessageBox.mBoxType.simpleNotification, "No results found in specified area");
        return false;
    }
    return true;