PyPN: Validate Your Xml

Have you tried playing with PyPN and PN’s scripts system yet? If not, then perhaps you should. A large number of requests on PN’s Feature Requests tracker could be implemented as scripts. Some perhaps not so elegantly as if they were built in, others perfectly.

To start looking at ways that PyPN enhances Programmer’s Notepad, let’s look at a very early feature request: Validate XML.

Here is a simple PyPN script that does just this, adding a command to the scripts window called Validate in the XML group. This can, of course, be mapped to a keyboard shortcut.

The script simply runs the contents of your document through expat. When your Xml is valid no output is printed, where there’s an error the output window will show you the details.

To use this code, just drop it in a file called something like in the scripts directory. You’ll need PyPN installed, along with Python 2.4 and the PyXml package. As of Python 2.5 expat is bundled so the extra package won’t be necessary.

import pn
import scintilla
from pypn.decorators import script
import xml.parsers.expat as expat

@script("Validate", "Xml")
def ValidateXml():
	editor = scintilla.Scintilla(pn.CurrentDoc())
	text = editor.GetText(0, editor.Length)

	parser = expat.ParserCreate()

		parser.Parse(text, True)
	except expat.ExpatError, ex:
		pn.AddOutput("Error: " + str(ex))