Path: csiph.com!fu-berlin.de!uni-berlin.de!not-for-mail From: Karim Newsgroups: comp.lang.python Subject: Re: Understanding how to quote XML string in order to serialize using Python's ElementTree Date: Sat, 9 Jan 2016 23:08:26 +0100 Lines: 133 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=windows-1252; format=flowed Content-Transfer-Encoding: 7bit X-Trace: news.uni-berlin.de +xCKAec1BLe18SmXHRf8/QA4amUjMhEvrS2L7ZvBm9ng== Return-Path: X-Original-To: python-list@python.org Delivered-To: python-list@mail.python.org X-Spam-Status: OK 0.000 X-Spam-Evidence: '*H*': 1.00; '*S*': 0.00; 'handler': 0.04; 'root': 0.04; 'subject:Python': 0.05; 'skip:" 60': 0.05; 'sys': 0.05; '"__main__":': 0.07; '-*-': 0.07; '__name__': 0.07; 'column': 0.07; 'data):': 0.07; 'data:': 0.07; 'formatting': 0.07; 'sanity': 0.07; 'utf-8': 0.07; 'coding:': 0.09; 'csv': 0.09; 'delimiter': 0.09; 'ide': 0.09; 'name):': 0.09; 'os.path': 0.09; 'script,': 0.09; 'stringio': 0.09; 'subject:string': 0.09; 'subject:using': 0.09; 'utilizing': 0.09; 'python': 0.10; 'syntax': 0.13; 'def': 0.13; "skip:' 30": 0.15; 'subject: \n ': 0.15; '(line': 0.16; 'guidance.': 0.16; 'ideally,': 0.16; 'idx': 0.16; 'idx,': 0.16; 'pythonic': 0.16; 'received:io': 0.16; 'received:psf.io': 0.16; 'row': 0.16; 'self)': 0.16; 'subject:XML': 0.16; 'syntaxerror:': 0.16; 'variations': 0.16; 'wrote:': 0.16; 'string': 0.17; 'element': 0.18; 'try:': 0.18; '(in': 0.18; 'variable': 0.18; '>>>': 0.20; 'windows': 0.20; 'to:2**1': 0.21; 'so.': 0.22; '"",': 0.22; 'assign': 0.22; 'pass': 0.22; 'this:': 0.23; 'tried': 0.24; 'import': 0.24; 'xml': 0.24; 'header:In-Reply-To:1': 0.24; 'header :User-Agent:1': 0.26; '(which': 0.26; 'skip:" 20': 0.26; 'skip:_ 20': 0.26; 'skip:# 10': 0.27; 'skip:e 30': 0.27; 'yield': 0.27; 'correct': 0.28; "skip:' 10": 0.28; 'quoting': 0.29; 'whitespace': 0.29; 'raise': 0.29; 'print': 0.30; 'skip:_ 10': 0.32; 'class': 0.33; 'message-id:@gmail.com': 0.34; 'file': 0.34; 'except': 0.34; 'received:google.com': 0.35; 'attempt': 0.35; 'follows:': 0.35; 'unknown': 0.35; 'received:74.125.82': 0.35; 'but': 0.36; 'there': 0.36; 'skip:m 40': 0.36; 'to:addr:python-list': 0.36; 'subject:: ': 0.37; 'method': 0.37; 'beyond': 0.37; 'feedback': 0.38; 'thank': 0.38; 'means': 0.39; 'data': 0.39; 'received:192': 0.39; 'skip:e 20': 0.39; 'skip:x 10': 0.40; 'to:addr:python.org': 0.40; 'your': 0.60; 'address': 0.61; 'charset:windows-1252': 0.62; 'information': 0.63; 'due': 0.65; 'here': 0.66; 'receive': 0.71; '0000': 0.84; "everything's": 0.84; 'specs:': 0.84 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20120113; h=subject:to:references:from:message-id:date:user-agent:mime-version :in-reply-to:content-type:content-transfer-encoding; bh=KjruKH8mxPVvfi6pYj1kFGI9rr+5WivUp7V1GUdWLlI=; b=AWq7aRHiS4b9FSidJp/HOwKsON2UtHnshFjV+HZUkhhPRyJYjJYmfP4D/5uws7W/SG ZAo8aYSqMoOXX9cexYsEOgHd3hhLK2Y05S14L8RhWJEe2H5oHI6TlE2KDtV2A4dNylg8 kjjKFsbQz9RY9Ijmzuh5rMEf4g8qH5XRPI494M9RtM73IVznMQDnLmZxYAeDjtqIgG5/ 0MbA0GNTHGivHv/XyeUnkW3HClpOcP1nv0yyNGswnlyxB1D3BUxl9WX76Fcw9rgCbs1a 1/frwOu/NnaHkA+TcTaaVjvOPSBV2dYv+ghhjlIFVcdPFRxTSrD+ScdBGa2wBeXNonUy Pu2w== X-Received: by 10.28.30.138 with SMTP id e132mr5360769wme.86.1452377308772; Sat, 09 Jan 2016 14:08:28 -0800 (PST) User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:38.0) Gecko/20100101 Thunderbird/38.4.0 In-Reply-To: X-BeenThere: python-list@python.org X-Mailman-Version: 2.1.20+ Precedence: list List-Id: General discussion list for the Python programming language List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Xref: csiph.com comp.lang.python:101414 On 09/01/2016 21:54, kbtyo wrote: > My specs: > > Python 3.4.3 > Windows 7 > IDE is Jupyter Notebooks > > What I have referenced: > > 1) http://stackoverflow.com/questions/1546717/python-escaping-strings-for-use-in-xml > > 2) > http://stackoverflow.com/questions/7802418/how-to-properly-escape-single-and-double-quotes > > 3)http://stackoverflow.com/questions/4972210/escaping-characters-in-a-xml-file-with-python > > > Here is the data (in CSV format) and script, respectively, (I have tried variations on serializing Column 'E' using both Sax and ElementTree): > > i) > > A,B,C,D,E,F,G,H,I,J > "3","8","1","2312285SChecking10","0000',0001,0070,","1967-12-25 22:18:13.471000","2005-12-25 22:18:13.768000","2","70","0" > > ii) > > #!/usr/bin/python > # -*- coding: utf-8 -*- > import os.path > import sys > import csv > from io import StringIO > import xml.etree.cElementTree as ElementTree > from xml.etree.ElementTree import XMLParser > import xml > import xml.sax > from xml.sax import ContentHandler > > class MyHandler(xml.sax.handler.ContentHandler): > def __init__(self): > self._charBuffer = [] > self._result = [] > > def _getCharacterData(self): > data = ''.join(self._charBuffer).strip() > self._charBuffer = [] > return data.strip() #remove strip() if whitespace is important > > def parse(self, f): > xml.sax.parse(f, self) > return self._result > > > def characters(self, data): > self._charBuffer.append(data) > > def startElement(self, name, attrs): > if name == 'Response': > self._result.append({}) > > def endElement(self, name): > if not name == 'Response': self._result[-1][name] = self._getCharacterData() > > def read_data(path): > with open(path, 'rU', encoding='utf-8') as data: > reader = csv.DictReader(data, delimiter =',', quotechar="'", skipinitialspace=True) > for row in reader: > yield row > > if __name__ == "__main__": > empty = '' > Response = 'sample.csv' > for idx, row in enumerate(read_data(Response)): > if idx > 10: break > data = row['E'] > print(data) # The before > data = data[1:-1] > data = ""'{}'"".format(data) > print(data) # Sanity check > # data = '0000',0001,0070,' > try: > root = ElementTree.XML(data) > # print(root) > except StopIteration: > raise > pass > # xmlstring = StringIO(data) > # print(xmlstring) > # Handler = MyHandler().parse(xmlstring) > > > Specifically, due to the quoting in the CSV file (which is beyond my control), I have had to resort to slicing the string (line 51) and then formatting it (line 52). > > However the print out from the above attempt is as follows: > > "0000' > 0000 > > File "", line unknown > ParseError: no element found: line 1, column 69 > Interestingly - if I assign the variable "data" (as in line 54) I receive this: > > File "", line 56 > data = '0000',0001,0070,' > ^ > SyntaxError: invalid token > > I seek feedback and information on how to address utilizing the most Pythonic means to do so. Ideally, is there a method that can leverage ElementTree. Thank you, in advance, for your feedback and guidance. I don't understand because this line 54 gives: >>> import xml.etree.cElementTree as ElementTree >>> data = '0000',0001,0070,' File "", line 1 data = '0000',0001,0070,' ^ SyntaxError: invalid syntax BUT IF you correct the string and remove the inner quote after 0000 everything's fine: >>> data = '0000,0001,0070, ' >>> root = ElementTree.XML(data) >>> root Karim