So, I’m writing a simple function to remove a XML node from a XML document. The easiest way to achieve this, as far as I can tell, is to:
- Get a reference to the node that will be removed (
ChildNode) - Get a reference to the node’s parent using the
ChildNode.ParentNodeproperty (ParentNode) - Call the
ParentNode.RemoveChild(ChildNode)method
Now, this works great if the child node is a XmlElement, but what if the child node was a XML attribute? According to the MSDN documentation for XmlNode.ParentNode, the property would return nothing, because “[attributes] do not have parents.“
Attributes most definitely do have “parents,” do they not? An attribute must be assigned to a XML element, so the XML element would be the attribute’s parent, in my mind.
Can someone clear up my misunderstanding, or clarify why the .NET Framework does not see attributes as having parents?
You can use the
XmlAttribute.OwnerElementto get the owner of an attribute.Your procedure will have to be modified to something like this:
Get a reference to the node that will be removed (
ChildNode).If the type of the node is
XmlAttributedowncast to that type (AttributeNode) and get a reference to the node’s parent using theAttributeNode.OwnerElementproperty (ParentNode). If not go to step 4.Call the
ParentNode.Attributes.Remove(AttributeNode)method. Skip remaining steps.Get a reference to the node’s parent using the
ChildNode.ParentNodeproperty (ParentNode).Call the
ParentNode.RemoveChild(ChildNode)method.So basically you have to give attributes special treatment reflecting the fact that they are not really part of a parent-child hierarchy but rather – well, attributes – of an XML element.