Simple xml parsing question

I have basically no experience parsing xml in Ignition / Python. I'm trying to figure out the easiest way I can parse the following xml:

<?xml version=1.0 encoding=utf-8?><serial>XA8287</serial>

...such that I can get the serial into a string for further manipulation. The serial in question here would be XA8287. This is taking place within a Web Dev script, Ignition version 8.1.32.

Do I need to import DocumentBuilderFactory as explained in this page? Or would the SAX Parser be better? I feel like I could arrive at something workable by playing around a bit but I have no idea what the 'best practice' method would be here...

For a small XML document like your example the DOM Parser / DocumentBuilderFactory example should be easier.

SAX (streaming) is harder to use but better memory-wise when dealing with large documents.

There's also the Python etree library you can probably find examples for here in the forum, but I think there's historically been weird / hard to track down errors when using that...

3 Likes

Related:

I highly recommend using my wrappers around java's native XML handlers.

Edit: This might be more helpful:

1 Like

The element tree library seems to be working ok for now:

def doPost(request, session):
	import xml.etree.ElementTree as ET
	xml = str(request['postData'])
	root = ET.fromstring(xml)
	serial = root.text
	...

And then it gets used once more at the end, after I construct an xml string:

	...
	root = ET.fromstring(xml_string)
	return root

IIRC, it can break if you feed it some unicode.

Don't use jython/python stdlib packages for things that can be done with java standard libraries.

2 Likes