Last time I wrote about comparing XML strings in .NET, and continuing that theme I’d like to discuss another handy XML trick. As the last article pointed out, not all XML strings are created equal. In fact, sometimes they are missing the necessary XML version and encoding information, like in the following sample XML:
So you want to compare two XML strings together to see if they are equal. Obviously, it would be easy to just compare the two strings using a regular string equality comparison and call it a day. However, what if the XML strings looked like the following:
All of the nodes, attributes and values are the same, but the formatting is way off. Obviously, a string equality comparison between these two would return false. Is there anything that can be done about this? Not to fear, .NET provides a pretty simple solution. Continue reading →
If you need to extract the data from an XML data type column to be used as part of query, and you need it to be a usable data type in MS-SQL, you can use the Value() method. Using the Value method, we can extract the data contained within an XML tag as a SQL Data Type. The Value() method takes two arguments:
XQuery and SQLType
The following returns the value stored in the second <SSID> tag as a VarChar(50):
— First we create an XML variable to store the data that we’ll use for this example
DECLARE @x xml
SET @x = ‘<NETWORKS>
<SSID> Wompsters University </SSID>
<SSID> Wompsters Inc </SSID>
— Select the second SSID value and specify that we’d like to return it as a VarChar(50), (Keep in mind the <SSID> position starts at 1, not 0)
SELECT @x.value(‘(//NETWORKS/SSID)’, ‘varchar(50)’);
— This will return the VarChar “Wompsters Inc”, which you could use like a normal String in any SQL query
Serialization is a process of converting an object into a stream of data, to easily transfer over the network or to save to disk. So, using this concept of serialization, we can serialize any object to XML string. Here is a person class that we can serialize.
Here is the code that takes the person object into string of xml format.
Using Serialization in .NET is provided by the System.Runtim.Serialization name space.
Once you have the XML string, now you can save it to disk, store it into database, or transfer over the network. Here is the deserialization method that takes serialized string of XML into the person object.
With the release of .NET 3.5, Microsoft has included a fun new tool for data serializing. The DataContractSerializer was introduced as a replacement for the current XmlSerializer class, and is the preferred XML data serializer of developers at ImageSource.
The DataContractSerializer class uses opt-in properties for it’s serialization rather than the XmlSerializer class’s opt-out methodology. This means that the programmer must specify what class properties are to included in serialization. It’s also up to the programmer to serialize fields, properties and non-public data.