Wednesday, March 7, 2012

Closing Tags

Is there a way to tell SQL Server not to contract closing tags for empty elements? I'm getting a conflict in an app in trying to determine changed data. I create an XML DOM document and write the xml to an xml column in the database.

If I write "<SomeOuterElement><SomeInnerElement></SomeInnerElement></SomeOuterElement>"

the column actually stores: "<SomeOuterElement><SomeInnerElement/></SomeOuterElement>"

Which is great for optimization, but the dom produces empty elements with separate closing tags. So when compared as strings, they appear to be different. (I don't have access to the code that's doing the actual comparison. It's a bit of a black box situation.)

So I need SQL Server to leave the XML alone, or I need a way for the DOM to produce the optimized XML. (This is VB. NET)

Any ideas? Thanks.

J

Whether an empty element is serialized as or should not matter as both ways are semantically equivalent, the element is empty both ways.

If you are using the .NET DOM implementation and want to serialize an empty element as then use the property IsEmpty as in this snippet:

Code Snippet

Dim XmlDoc As XmlDocument = New XmlDocument()

Dim Element As XmlElement = XmlDoc.CreateElement("root")

Dim Element1 As XmlElement = XmlDoc.CreateElement("element")

Element1.IsEmpty = True

Element.AppendChild(Element1)

XmlDoc.AppendChild(Element)

XmlDoc.Save(Console.Out)

But note that you get <element /> that way and not <element/> so string comparison might fail again. You will have to implement your own XmlWriter if you need more control over the serialization details. To implement your own XmlWriter you often subclass XmlTextWriter. However such attempts to make applications happy that don't understand XML fully is in my view an attempt to fix things on the wrong end, it should not matter to an application whether an empty element is marked up as <element/> or <element /> or <element></element>.

No comments:

Post a Comment