我正在学习Python 3,对此找不到任何解释。 以下函数从XML字符串中提取并返回内容:
import xml.etree.ElementTree as ET
import zlib
def parse_xml(session_id):
root = ET.ElementTree(ET.fromstring(session_id))
session_xml = root.findall(
'.//{http://www.api-url.com/API_Service/}StartSessionResult')[0].text
return session_xml
session_id
的示例值:
<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><StartSessionResponse xmlns="http://www.elektrotop3001.com/AAAA_Service/"><StartSessionResult><?xml version="1.0" encoding="utf-8"?><AUTHENTICATION><SESSSION ID="3btqqSR5AUQsnDVBQ3dd5LAj54rekna3HPox7vYe" /></AUTHENTICATION></StartSessionResult></StartSessionResponse></soap:Body></soap:Envelope>
示例结果值session_xml
:
<?xml version="1.0" encoding="utf-8"?><AUTHENTICATION><SESSSION ID="3btqqSR5AUQsnDVBQ3dd5LAj54rekna3HPox7vYe" /></AUTHENTICATION>
稍后我将session_xml
的字符串转换为带有.encode('utf-8')
的字节:
sess_short_xml = parse_xml(session_id)
sess_short_xml_bytes = sess_short_xml.encode('utf-8')
,问题在于它将\xef\xbb\xbf
添加到bytes对象。
当我像return
一样将样本纯字符串手动放置到return 'abc'
时,sess_short_xml_bytes
的值为b'abc'
,然后它不添加\xef\xbb\xbf
。
这是一个问题,因为稍后我将使用sess_short_xml_bytes
(需要类似字节的对象)从zlib.crc32
计算CRC,并且CRC结果无效,可能是因为\xef\xbb\xbf
。
有什么方法可以将XML内容提取并转换为字节而不进行修改吗?还是通过这种XML内容正确计算JAMCRC的方法?