runtime icon indicating copy to clipboard operation
runtime copied to clipboard

Inconsistent behavior of XmlAttributeCollection.InsertBefore and InsertAfter

Open plabovich opened this issue 11 years ago • 0 comments

I've noticed an inconsistent behavior of XmlAttributeCollection.InsertAfter(XmlAttribute newNode, XmlAttribute refNode) comparing to InsertBefore when the reference node is the last in the collection (the first for InsertBefore) and it's a duplicate of the new node. The duplicate node (attribute) needs to be removed before inserting. InsertAfter is unable to handle the case and throws System.ArgumentOutOfRangeException further in List<T>.Insert() due to an incorrectly calculated insert position, while InsertBefore does the job. I'm not sure if this case has any practical use, but might be worth fixing.

The following unit test reproduces the problem:

    [Fact]
    // [ActiveIssue("Throws argument out of range exception")]
    public void InsertAfterRemovesDupRefAttr()
    {
        const string attributeName = "existingAttr";
        const string attributeUri = "some:existingUri";
        XmlDocument doc = CreateDocumentWithElement();
        XmlElement element = doc.DocumentElement;
        element.Attributes.Append(doc.CreateAttribute("attr1", "some:uri1"));
        element.Attributes.Append(doc.CreateAttribute("attr2", "some:uri2"));
        XmlAttribute refAttr = element.Attributes.Append(doc.CreateAttribute(attributeName, attributeUri)); //dup
        XmlAttribute newAttr = doc.CreateAttribute(attributeName, attributeUri);

        XmlAttributeCollection target = element.Attributes;
        target.InsertAfter(newAttr, refAttr); // throws

        // Assert...
    }

A similar case (the reference attribute is the first in the collection) works for InsertBefore:

    [Fact]
    public void InsertBeforeRemovesDupRefAttr()
    {
        const string attributeName = "existingAttr";
        const string attributeUri = "some:existingUri";
        XmlDocument doc = CreateDocumentWithElement();
        XmlElement element = doc.DocumentElement;
        XmlAttribute refAttr = element.Attributes.Append(doc.CreateAttribute(attributeName, attributeUri)); //dup
        element.Attributes.Append(doc.CreateAttribute("attr1", "some:uri1"));
        element.Attributes.Append(doc.CreateAttribute("attr2", "some:uri2"));
        XmlAttribute newAttr = doc.CreateAttribute(attributeName, attributeUri);

        XmlAttributeCollection target = element.Attributes;
        target.InsertBefore(newAttr, refAttr);

        // Assert...
    }

plabovich avatar Mar 31 '15 23:03 plabovich