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:
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”.
<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.
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) _
.ToString())
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.
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.




Recent Comments