Don't "p" on your XAttributes..

Posted Mon, Nov 26 2007 20:26 by bill

If you programmatically add attributes with namespaces to an XElement, when the XElement is written out it will give each attribute a namespace prefix and then define a xmlns for that prefix.  The way XElement does this is first it examines the namespaces already active and also those defined in the element for a match. If it doesn't find a match, it then creates a new prefix based on the count of the current namespaces in scope, e.g p1, p2, p3,....pn.

Now sadly, although it did first scan for namespaces, it appears it doesn't scan for prefixes in the current element *after* the current attribute. It does scan for previous declared prefixes, and will use one if the namespace matches. If the namespace doesn't match but a prefix clashes with the proposed prefix, the prefix is added a 0, e.g p10, p20, ... pn0. If that one also clashes then the number will be increased e.g p11, p21, ... pn1. And so forth.

The problem is it doesn't check for clashes inside the element it arbitrarily adds a namespace to. This code causes an exception due to the same attribute being named twice.

 

   Dim books = New XElement("books")

   books.Add(New XAttribute("{abc}attrib1", "one"))

   books.Add(New XAttribute(XNamespace.Xmlns.GetName("p1"), "zzz"))

 

The moral of the story is don't use "pn" for your namespace prefixes. (where n is any integer). You end up potentially "p"ing on your code ;)

Filed under: , , , ,