Python XML Iterparse halt on text

221 Views Asked by At

I am new to python, using 3.x, and am running into an issue with an XML file that I'm testing/learning on. When I look at the raw file (which is ASCII encoded btw), the issue (I'm pretty sure) is that there's a U+00A0 code in there.

The XML is as follows:

<?xml version="1.0" encoding="utf-8"?>
<XMLSetData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.clientsite.com/subdir/r2.4/v1">
  <FileCreationDate>2018-05-05T11:35:44.1043858-05:00</FileCreationDate>
  <XMLSetDataList>
    <DataIDNumber>99345346</DataIDNumber>
    <DataName>RSRS TVL5697 ULL  Georgetown</DataName>
  </XMLSetDataList>
</XMLSetData>

Using Notepad++, it shows me that the text has "xA0 " instead of " " (two spaces) between ULL and Georgetown. So when I do the code below:

import xml.etree.ElementTree as ET    
events = ("end", "start-ns", "end-ns")

for event, elem in ET.iterparse(xml_file, events=events):
        if event == "end":
            eltag = elem.tag
            eltext = elem.text
            print( eltag, eltext)

It gives me an error stating:

  File "C:\Users\d\AppData\Local\Programs\Python\Python37-32\lib\xml\etree\ElementTree.py", line 1222, in iterator
    yield from pullparser.read_events()
  File "C:\Users\d\AppData\Local\Programs\Python\Python37-32\lib\xml\etree\ElementTree.py", line 1297, in read_events
    raise event
  File "C:\Users\d\AppData\Local\Programs\Python\Python37-32\lib\xml\etree\ElementTree.py", line 1269, in feed
    self._parser.feed(data)
  File "<string>", line None
xml.etree.ElementTree.ParseError: not well-formed (invalid token): line 6, column 30

How do I fix this / get around it? If I remove the xA0 part, it parses fine, but obviously something like this may come up again, and I'd like to programmatically handle it.

0

There are 0 best solutions below