Why doesn't the XML attribute have a "parent" element in .NET?

So, I am writing a simple function to remove an XML node from an XML document. The easiest way to achieve this, as far as I can tell, is as follows:

  • Get the link to the node to be removed ( ChildNode

    )
  • Get reference to parent node using property ChildNode.ParentNode

    ( ParentNode

    )
  • Call method ParentNode.RemoveChild(ChildNode)

Now this works fine if the child node is XmlElement

, but what if the child node was an XML attribute? According to the MSDN documentation for XmlNode.ParentNode

, the property will return nothing

because "[attributes] have no parents."

Attributes most definitely have "parents", don't they? The attribute must be assigned to the XML element, so the XML element will be the parent of the attribute in my opinion.

Can someone clear up my misunderstanding or explain why the .NET Framework doesn't see attributes as having parents?

+3


source to share


2 answers


You can use XmlAttribute.OwnerElement

to get the owner of an attribute.

Your procedure should be changed to the following:



  • Get a reference to the node to be removed ( ChildNode

    ).

  • If the node type is XmlAttribute

    not available for that type ( AttributeNode

    ) and get a reference to the parent node using property AttributeNode.OwnerElement

    ( ParentNode

    ). If you don't go to step 4.

  • Call the method ParentNode.Attributes.Remove(AttributeNode)

    . Skip the rest of the steps.

  • Get a reference to the parent node using property ChildNode.ParentNode

    ( ParentNode

    ).

  • Call the method ParentNode.RemoveChild(ChildNode)

    .

So basically you should pay special attention to the attribute attributes reflecting the fact that they are not part of the parent-child hierarchy, but rather - well, attributes - of the XML element.

+9


source


Good question and one where the answer lies in the spec and not with Microsoft (some might say this time ...).

At the W3C, we can find a specification that gets to override what any of us can feel is intuitively obvious. In it, I find the word parent only once , in this context :

[Definition: As a consequence, for every non-root C element in the document, there is another P element in the document, such that C is in the content of P, but not in the content of any other element, i.e. in the content P. P is referred to as the parent element C, and C as child P.]



Note that "item" here only refers to actual items; and "content" only refers to child elements. The concept XmlNode

is an abstraction (which is not specified in the spec) that is part of the library, not a standard.

I suppose MS could have done an implementation ParentNode

for the attributes returning the control, but then you want the ChildNodes

element to include the attributes? This seems less desirable.

+3


source







All Articles