Working with XElement Names

XElement has a slightly different way of talking about XML than what WCF uses. This can lead to subtle bugs if you're not careful.

Everywhere you see XML used in WCF, it is processed using an XmlReader and XmlWriter. These classes allow you to work with XML with extremely high performance but the classes themselves are not particularly easy to use. For someone who hasn't used this particular model before, it is surprisingly difficult to create and build up XML documents. XElement is the center of a newer and much easier library of classes for working with XML although it doesn't get quite the same performance as XmlReader and XmlWriter, particularly when doing stream processing.

When working with WCF you'll frequently see a Name and Namespace pair of parameters. These parameters are both string types. The name is the common name and the namespace qualifies the common name so that many people can choose names without having to worry about conflicts. Since the namespace is primarily for avoiding conflicts, some people like to cheat a bit and just use the name in comparisons when conflicts are unlikely.

XElement also has a Name. However, rather than being a string, this name is actually the XName type, which contains both the common name and the namespace. Some people who are used to using the Name in WCF translate that to the Name in XElement, which represents a change in behavior. The correct parallel would be element.Name.LocalName instead of element.Name.

This difference can be hard to spot because it frequently just happens to work if you change both sides of the comparison in the same way at the same time. Additionally, your choice of serializer and contract definition may affect the default namespace. A lot of the older mechanisms and tools used an empty default namespace so again many things will happen to work. Other serializer and contract mechanisms, such as with data contracts, generate temporary namespace, which is much more likely to mysteriously stop working due to failed matches when you change the comparison behavior.

Next time: Examining Header Values