XML Literals



I love XML Literals in VB.NET. They're a great way of generating valid XML instead of dealing with giant concatenated strings.

After discussing testing an XML Processing type class with a colleague this morning I thought I'd show him how this could be achieved quite nicely using XML literals. In his case; the code base is C# but that's not a problem for us.
Imports System.Text
Imports Microsoft.VisualStudio.TestTools.UnitTesting
<TestClass()>
Public Class GivenAValidXmlPerson
Private _person As XDocument
Dim _id As Integer
Dim _firstName As String
Dim _lastName As String
Dim _dob As Date
Dim _results As MuonLab.Validation.ValidationReport
<TestInitialize()>
Public Sub Setup()
Me._id = 1
Me._firstName = "Dom"
Me._lastName = "Finn"
Me._dob = New DateTime(2000, 1, 1)
Me._person =
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<people>
<person>
<id><%= _id %></id>
<firstname><%= _firstName %></firstname>
<lastname><%= _lastName %></lastname>
<dob><%= _dob %></dob>
</person>
</people>
Dim validator = New XmlPersonValidator()
Me._results = validator.Validate(Me._person)
End Sub
<TestMethod()>
Public Sub TheValidatorShouldBeValid()
Assert.IsTrue(Me._results.IsValid)
End Sub
End Class
We are able to create an XML document directly in the code instead of concatenating a string and parsing that into an XDocument. You get really nice intellisense whilst creating the document and you can also loop over a collection for example to generate the XML.

The whole project can be found on my Github here: https://github.com/DominicFinn/XmlLiteralsForTesting 

Let me know if you like it! For me, it's all part of the "write language for the job" ethos.

Beth Massi is a good source of VB.NET tips in general, this are some nice tricks that you can use XML Literals for: http://blogs.msdn.com/b/bethmassi/archive/2007/10/26/xml-literals-tips-tricks.aspx

She also did a DotNetRocks TV episode on XML Literals that you can find here: http://www.dnrtv.com/default.aspx?showNum=119
SHARE

Dom Finn

  • Image
  • Image
  • Image
  • Image
  • Image
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment