Monday , 24 April 2017
Home » Refactoring and Extracting XML Literals

Refactoring and Extracting XML Literals

I was recently given a task to refactor and extract the XML Literals and here’s my solution, which isn’t the best, but it is good enough for now.

Let’s say you have this code:

[sourcecode language=”vb”] Dim number1 As Integer = 5
Dim number2 As Integer = 10
Dim xml = <MyXml><%= number1 %><%= number2 %></MyXml>

Where you have an embedded variable using XML Literals within this block of XML. You want to extract that XML out to a file, instead of embed it into the language. Here’s a solution I came up with, and will definitely be thinking of how to solve this problem a little less “hack-ishly”.

[sourcecode language=”xml”] <MyXml>{0}{1}</MyXml>

So I extracted out the XML and replaced all embedded XML Literal code with {0}..{1}..{n}. Or anything that’s unique for replacement.

[sourcecode language=”vb”] Public Shared Function GetXml(ByVal number1 As Integer, ByVal number2 As Integer)
Dim template = New StringBuilder(XElement.Load("myxml.xml").ToString())
Return XElement.Parse( _
template.Replace("{0}", number1) _
.Replace("{1}", number2) _
End Function

Then I read the xml file and spit it out as a string, replace all the {0}..{1}..{n} with the actual parameters. I was actually going to use String.Format (hence the chosen {0}..{1}..{n} replacement) but couldn’t seem to get it to work.

[sourcecode language=”vb”] Dim number1 As Integer = 5
Dim number2 As Integer = 10
Dim xml = GetXml(number1, number2);

So all I do is just replace that entire block of XML Literal with a call to the method. That’s how you can refactor and extract out the XML Literals from Visual Basic .NET code. If you know of a better way to do this, please post a comment with your solution.

Note: Please mind my Visual Basic .NET code. It’s not my first language.

About Justin Lee

Check Also

Samsung Galaxy Note7 – “Eye-ing” the Next Evolution in the Galaxy Note Series

The next generation Samsung Galaxy Note7 combines both style and innovative features and top of …

Leave a Reply