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:
Good morning Gerardo,
Yes, but you'll have to generate the XML piece by piece. I would use my helper script module for this kind of work: xml.py (Place it in your project script library.)
Make a somewhat generic row-to-xml function in a project library, perhaps like so:
rowTemplate = """<table><row/></table>"""
# Produce downloadable XML bytes from a dictionary of column values.
def rowToXML(valuesDict):
dom = xml.strToDoc(rowTemplate)
rowNode = dom.getElementsByTagName("row")[0]
for k, …
I highly recommend using my wrappers around java's native XML handlers.
Edit: This might be more helpful:
Here is the current block of code where I am using the parse with jython solution that tends to lock up every so often.
import xml.etree.ElementTree as ET
#read the xml filef
for device in importDevices:
filePath = '%s/%s.xml' % (rootPath,device)
#print 'reading %s' % filePath
deviceStart = system.date.now()
#logger.info('Before: tree = ET.parse(filePath)')
tree = ET.parse(filePath)
#logger.info('After: tree = ET.parse(filePath)')
xmlFile = tree.getroot()
I made the f…
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