Will "the Mighty" Strohl

HOW TO: Load an XPathDocument Using a String Object

For some odd reason, the XPathDocument class does not support loading the object using a string.  However, this seems to be an integral requirement for some applications where the XML is generated and parsed on-the-fly.  Here's how to do that...

Dim byteObj() As Byte
byteObj = System.Text.Encoding.UTF8.GetBytes(SerializedObject)
Dim memStr As System.IO.MemoryStream = New System.IO.MemoryStream(byteObj)
Dim xpathDoc As XPathDocument = New XPathDocument(memStr)

That is only four lines of code.  Hey!  That's pretty good...  But what if you didn't want to use four lines?  Can't we bring this down to less lines of code?  Yes!  Here is the same example in only two lines of code, and less memory overhead, because there are also less objects.

Dim memStr As System.IO.MemoryStream = New System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(SerializedObject))
Dim xpathDoc As XPathDocument = New XPathDocument(memStr)

What if you wanted to globalize this to make it even easier?  Couldn't you add this as a shared/static function to an existing class?  Sure, but it could get even better... 

You can take that a step further by extending the XPathDocument class, for use in your entire application.  This way, you have then limited those two lines of code to one - each time you do it.  Don't forget that your footprint is also smaller since you are extending an existing class.

Imports System.IO
Imports System.Text
Imports System.Xml
Imports System.Xml.XPath
Namespace MyCompany.Extensions
    Public Class XPathDocument         Inherits System.Xml.XPath.XPathDocument
        Public Sub New(ByVal xmlString As String)             MyBase.New(New MemoryStream(Encoding.UTF8.GetBytes(xmlString)))         End Sub
    End Class
End Namespace

Now, you can call this from anywhere in your code like so:

Dim strXml As String = "<rootNode><element1>somevalue</element1></rootNode>"
Dim xpathDoc As New MyCompany.Extensions.XPathDocument(strXml)

Now, we have reduced this to one line of code! :) Have fun!



blog comments powered by Disqus