Question

I try to remove some XmlElements from my Xml file in C#2.0. I can remove it successfully with XmlNode.Remove() method. But there is no Remove method in XmlElement.

I googled and found this.

elements are a type of node. In fact, if you look at the members of XmlNode and XmlElement in the .NET Framework, you will see that they are very much alike, but XmlElement has more going on. It inherits XmlNode and then is further customized. This is because an element is more specialized. A node is more general in scope. The document is a node, a processing instruction is a node, and so forth. Elements are different. If you look at the XmlNodeType property of an element, you will see that it is Element, one of the many types of nodes you find.

If element are a type of node, then why I can't use remove command. Then how?

XmlDocument doc_AlarmSettingUp = new XmlDocument();
doc_AlarmSettingUp.Load(xmlFile_AlarmSettingUp);
XmlNode rootDest = doc_AlarmSettingUp.SelectSingleNode("/Equipment/AlarmSettingUp/EnabledALIDs");
foreach (XmlElement el_AlarmSettingUp in doc_AlarmSettingUp.SelectNodes("/Equipment/AlarmSettingUp/EnabledALIDs/ALID"))
{
    XmlElement outEl;
    if (lookup.TryGetValue(el_AlarmSettingUp.GetAttribute("alid"), out outEl))
    {
        // exists; element now in "other"
        // Console.WriteLine("exists");
    }
    else
    {
        // doesn't exist
        Console.WriteLine("doesn't exist");
        // Then How can I remove element with an element method? Thanks.
    }
}
Was it helpful?

Solution

The following code should work on any XmlElement:

if (outEl.ParentNode != null) outEl.ParentNode.RemoveChild(outEl);

OTHER TIPS

What are you trying to do with the code above? It doesn't relate to the question as far as I can see.

What is the problem with calling Remove on an XmlElement (which is an XmlNode)?

As far as I can see, XmlNode doesn't have a Remove() method either. It does have a RemoveChild(XmlNode) method, and so does XmlElement. You should use RemoveChild of the parent element to remove the child element.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top