Python parsing XML file encountered encoding parsing problem

Source: Internet
Author: User

When parsing XML files using Python, parsing is ok if the header file of the XML file is encoded in the UTF-8 format, but if it is the other format, the following exception will appear:

Xml.parsers.expat.ExpatError:unknown encoding


Therefore, in order to ensure the normal operation of the program, we need to encode the read file.

1, first will read the characters from the original encoding parsing, and encoded into utf-8;

2, modify the XML encoding;

The code is as follows:

Import sysimport osimport datetimeimport timeimport stringfrom urllib import unquoteimport mysqldbimport Xml.parsers.expatimport Xml.etree.ElementTree as Etreeimport typesimport httplibimport urllib2import urllibimport Jsonimport redef readdatafromnetwork (URL): req = urllib2. Request (url) rd = Urllib2.urlopen (req) readdata = Rd.read () return readdata# <! [cdata[http://j.xywy.com/il_sii_27.htm]]>def parsexmlstr (_str): try:# encode string encoding _str = unquote (_str) _str = _ Str.decode (' GBK '). Encode (' Utf-8 ') print _str[0:100]except exception,ex:print ' ERROR ' # Modify the encoding of the XML file _STR = re.sub (' GBK ' , ' Utf-8 ', _str) xmldoc = etree.fromstring (_str) childlist = Xmldoc.getchildren () for node in childlist:str_value = Node.fin D ("Display/url"). Textif str_value.find (' CDATA ')! = -1:print ' haha '

The output results are as follows:

<?xml version= "1.0" encoding= "GBK"?><document><item><key> pertussis </key><display> <title><?xml version= "1.0" encoding= "Utf-8"?><document><item><key> pertussis </key> <display>


Python parsing XML file encountered encoding parsing problem

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.