views:

27

answers:

2

I have a string:

Dim strXMLTags As String = "<tags><test>1</test></tags>"

And I want to verify that all opening tags have a closing tag in the proper place. So if I put the previous string through, it'd work. However, if I put:

Dim strXMLTags As String = "<tags><test>1</test>"

Then I want it to give me an error. Is there an XML structure checker or something of the sorts? Or should I just try and load it to an XML document and if it errors then, then I know. Thanks.

+1  A: 

The easiest way would indeed be to try loading it into an xml document, and see if it crashes or not.

Joachim VR
Dern. I wish there were more boolean functions. :)
XstreamINsanity
You could always make one, an extension method on the string-class, for example.
Joachim VR
I'm trying to create as little new code as possible. I had/have one, but I'm using indexes, and cutting the strings, and I've only tested on examples given to me so I'm not sure if they'd work in every situation. And I don't have much time to test, need to get the product done. Thanks.
XstreamINsanity
A: 

Well I wouldn't know of a one-liner, but there are ways to check for valid XML:

  1. XSDs
  2. HTML Tidy
  3. Creating a temporary XML file and checking it's validity

1: XSDs - no need to explain here. When you have a correct schema for your XML you can validate against an XSD and see errors right away, this way you would even find missings tags etc.

2: HTMLTidy is the best resource for cleaning up messy HTML code. I am sure you could create something to only check your code. Check the HTMLTidy SourceForge page and a Tidy .NET Implementation here.

3: Temp XML - (my personal favorite) just create a new XmlTextReader and after writing your XML somewhere temporary read it in again and check for errors. There is some sample code on this page, it uses a ValidationSchema though which you might not have? Actually there is are some posts about XML Validation in VB.Net on that page.

moontear