Skip to main content
 首页 » 编程设计

python之使用 dicttoxml 模块从字典生成时,xml 字符串包含在 b'xml_string>' 中

2025年05月04日18lautakyan007

我正在使用 dicttoxml用于将字典转换为 xml 的模块。

代码:

cfg_dict = { 'mobile' : 
                { 'checkBox_OS' : 
                  { 'status' : 'None',  
                    'radioButton_Andriod' : 
                      { 'status' : 'None', 
                        'comboBox_Andriod_Brands' : 'LG'}, 
                    'radioButton_Windows' : 
                      { 'status' : 'None', 
                        'comboBox_Windows_Brands' : 'Nokia'}, 
                    'radioButton_Others' : 
                      { 'status' : 'None', 
                        'comboBox_Others_Brands' : 'Apple'}}, 
                  'checkBox_Screen_size' : 
                    { 'status' : 'None', 
                      'doubleSpinBox_Screen_size' : '5.0' }} 
              }         
 
from dicttoxml import dicttoxml 
xml = dicttoxml(self.cfg_dict) 
print (xml) 

输出:

b'<?xml version="1.0" encoding="UTF-8" ?><root><mobile type="dict"><checkBox_OS type="dict"><radioButton_Andriod type="dict"><status type="bool">false</status><comboBox_Andriod_Brands type="str">Sony</comboBox_Andriod_Brands></radioButton_Andriod><radioButton_Windows type="dict"><status type="bool">false</status><comboBox_Windows_Brands type="str">HTC</comboBox_Windows_Brands></radioButton_Windows><status type="bool">false</status><radioButton_Others type="dict"><status type="bool">false</status><comboBox_Others_Brands type="str">Apple</comboBox_Others_Brands></radioButton_Others></checkBox_OS><checkBox_Screen_size type="dict"><doubleSpinBox_Screen_size type="float">5.0</doubleSpinBox_Screen_size><status type="bool">false</status></checkBox_Screen_size></mobile></root>' 

不知道为什么要用b''括起来。如何在没有这个 b'' 的情况下生成 xml 字符串?

当打开包含此内容的 xml 文件时,浏览器也会给出错误消息。

请您参考如下方法:

这是 Python 3 中非 Unicode 字符串的正常表示。在 Python shell 中试试这个:

>>> type("foo") 
<class 'str'> 
>>> type(b"foo") 
<class 'bytes'> 
>>> type("Rübe") 
<class 'str'> 
>>> type(b"Rübe") 
  File "<stdin>", line 1 
SyntaxError: bytes can only contain ASCII literal characters. 

所以一切正常。你没有问题。

另见 str对比bytes .

编辑:

了解编码和解码的工作原理。

>>> s = "Rübe" 
>>> e = s.encode("UTF-8") 
>>> print(e) 
b'R\xc3\xbcbe' 
>>> type(e) 
<class 'bytes'> 
>>> d = e.decode("UTF-8") 
>>> d 
'Rübe' 

所以只需使用 my_byte_string.decode(my_encoding) ,其中 my_encoding 可能是 "UTF-8"。