Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #101415
| Path | csiph.com!fu-berlin.de!uni-berlin.de!not-for-mail |
|---|---|
| From | Karim <kliateni@gmail.com> |
| 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:23:54 +0100 |
| Lines | 120 |
| Message-ID | <mailman.101.1452378242.2305.python-list@python.org> (permalink) |
| References | <d0a2acdb-857c-47c5-a28d-422a8fc4cc74@googlegroups.com> |
| Mime-Version | 1.0 |
| Content-Type | text/plain; charset=windows-1252; format=flowed |
| Content-Transfer-Encoding | 7bit |
| X-Trace | news.uni-berlin.de +OVF/qXLPAFJDN4LhHgVGQZAkAMAFo4vqD3dbrjzsuLA== |
| Return-Path | <kliateni@gmail.com> |
| 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; 'reformat': 0.09; 'script,': 0.09; 'stringio': 0.09; 'subject:string': 0.09; 'subject:using': 0.09; 'utilizing': 0.09; 'python': 0.10; '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; 'windows': 0.20; 'to:2**1': 0.21; 'so.': 0.22; '"",': 0.22; 'assign': 0.22; 'rid': 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; "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; 'should': 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; '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=Ne2FG61wsqtoEjkGoOPQIqDsCsuYc7vKPAN5mlsZeK0=; b=AT5/NIM5/+fok1pexh9d6YXpOSfCbA+EsqKiEs49TJ2w8oqxbDHKzl5NqzrsTmWioi ils5gefgoA6YpzhCsJ2jFZM1OWwa/i3RfswtqhwS7iF6hKKjpxU5YQ0SgjvY1Wt6LCAr pEt7yI0iKOe16XJHxjQgoaKmzfdhwU/4wcmu+rZfdv0dcgQ5AxT2nl+29rIg2H03K89J B7nTom41Fzfs99d5PEQuniqejpntYW7VR7VZdevJdc1kbKUf85/7umpr1ST9fdBEXUfq QcJKSX92qNDMcVWnB2YrBcaINru/NS3QkpOhJGxUfYMEbpvm8dl0P5JMrMfsFr/kLfvF PItQ== |
| X-Received | by 10.195.12.75 with SMTP id eo11mr5043457wjd.50.1452378235682; Sat, 09 Jan 2016 14:23:55 -0800 (PST) |
| User-Agent | Mozilla/5.0 (X11; Linux x86_64; rv:38.0) Gecko/20100101 Thunderbird/38.4.0 |
| In-Reply-To | <d0a2acdb-857c-47c5-a28d-422a8fc4cc74@googlegroups.com> |
| X-BeenThere | python-list@python.org |
| X-Mailman-Version | 2.1.20+ |
| Precedence | list |
| List-Id | General discussion list for the Python programming language <python-list.python.org> |
| List-Unsubscribe | <https://mail.python.org/mailman/options/python-list>, <mailto:python-list-request@python.org?subject=unsubscribe> |
| List-Archive | <http://mail.python.org/pipermail/python-list/> |
| List-Post | <mailto:python-list@python.org> |
| List-Help | <mailto:python-list-request@python.org?subject=help> |
| List-Subscribe | <https://mail.python.org/mailman/listinfo/python-list>, <mailto:python-list-request@python.org?subject=subscribe> |
| Xref | csiph.com comp.lang.python:101415 |
Show key headers only | View raw
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","<Request TransactionID="3" RequestType="FOO"><InstitutionISO /><CallID>23</CallID><MemberID>12</MemberID><MemberPassword /><RequestData><AccountNumber>2</AccountNumber><AccountSuffix>85</AccountSuffix><AccountType>S</AccountType><MPIAcctType>Checking</MPIAcctType><TransactionCount>10</TransactionCount></RequestData></Request>","<Response TransactionID="2" RequestType="HoldInquiry"><ShareList>0000',0001,0070,</ShareList></Response>","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 = '<Response TransactionID="2" RequestType="HoldInquiry"><ShareList>0000',0001,0070,</ShareList></Response>'
> 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:
>
> "<Response TransactionID="2" RequestType="HoldInquiry"><ShareList>0000'
> <Response TransactionID="2" RequestType="HoldInquiry"><ShareList>0000
>
> File "<string>", 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 "<ipython-input-80-7357c9272b92>", line 56
> data = '<Response TransactionID="2" RequestType="HoldInquiry"><ShareList>0000',0001,0070,</ShareList></Response>'
> ^
> 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.
In fact to get rid of double quote simply create your csv reader like that:
reader = csv.DictReader(data, dialect='excel', skipinitialspace=True)
You should then don't need to slice data variable and reformat it.
Karim
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
Understanding how to quote XML string in order to serialize using Python's ElementTree kbtyo <ahlusar.ahluwalia@gmail.com> - 2016-01-09 12:54 -0800 Re: Understanding how to quote XML string in order to serialize using Python's ElementTree Karim <kliateni@gmail.com> - 2016-01-09 23:08 +0100 Re: Understanding how to quote XML string in order to serialize using Python's ElementTree Karim <kliateni@gmail.com> - 2016-01-09 23:23 +0100 Re: Understanding how to quote XML string in order to serialize using Python's ElementTree Saran Ahluwalia <ahlusar.ahluwalia@gmail.com> - 2016-01-09 18:13 -0500 Re: Understanding how to quote XML string in order to serialize using Python's ElementTree Saran Ahluwalia <ahlusar.ahluwalia@gmail.com> - 2016-01-09 18:15 -0500 Re: Understanding how to quote XML string in order to serialize using Python's ElementTree Karim <kliateni@gmail.com> - 2016-01-10 00:30 +0100
csiph-web