简体   繁体   English

Python 3 lxml.Objectify

[英]Python 3 lxml.Objectify

I have a small script that makes requests with httplib2 which returns the response body as bytes.我有一个小脚本,它使用httplib2发出请求,它将响应正文作为字节返回。 I normally want to immediately decode it to str so that my code can work as it previously did with 2.7.我通常想立即将其解码为 str 以便我的代码可以像以前在 2.7 中那样工作。

However, when the response is XML with encoding as the first line, lxml.objectify fails in python 3 as it expects bytes not str.但是,当响应是 XML 并且第一行是编码时, lxml.objectify在 python 3 中失败,因为它期望字节不是 str。 What is the best way to go from XML str to a objectified object in Python 3? go 从 XML str 到 object 中的物化 object 的最佳方法是什么?

To parse xml from a string using lxml , you can use .fromstring() method.要使用lxml从字符串中解析xml ,可以使用.fromstring()方法。

Example:例子:

from lxml import etree

xml = '<a xmlns="test"><b xmlns="test"/></a>'

root = etree.fromstring(xml)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM