简体   繁体   English

如何将 XML 树 object 转换为字节 stream? Python

[英]How to convert an XML tree object to bytes stream? Python

I have a function that saves files to a db, but this one requires a bytes stream as parameter.我有一个 function 将文件保存到数据库,但是这个需要一个字节 stream 作为参数。 Something like:就像是:

write_to_db("File name", stream_obj)

Now, I want to save a XML;现在,我想保存一个 XML; I am using the xml library.我正在使用 xml 库。

import xml.etree.cElementTree as ET

Is there a function that convert the xml object to bytes stream?是否有一个 function 将 xml object 转换为字节 ZF7B44CFAFD5C52223D5498196 The solution I got was:我得到的解决方案是:

  • Save it locally with the function write用 function 写入本地保存
  • Retrieve it with "rb" to get the file as bytes用“rb”检索它以获取文件为字节
  • Now that I have the bytes stream, save it with the function mentioned现在我有了字节 ZF7B44CFFAFD5C52223D5498196C8A2E7BZ,用提到的 function 保存它
  • Delete the file删除文件

Example:例子:

# Saving xml as local file
tree = ET.ElementTree(ET.Element("Example")
tree.write("/This/is/a/path.xml")

# Reading local file as bytes
f = open("/This/is/a/path.xml", "rb")

# Saving to DB
write_to_db("File name", f) # <--- See how I am using "f" cuz I opened it as bytes with rb

# Deleting local file
os.remove("/This/is/a/path.xml")]

But is there a function from the xml library that returns automatically the bytes stream?但是是否有来自 xml 库的 function 自动返回字节 stream? Something like:就像是:

tree = ET.ElementTree(ET.Element("Example")
bytes_file = tree.get_bytes() # <-- Like this?

# Writing to db
write_to_db("File name", bytes_file)

This so I can prevent creating and removing the file in my repository.这样我就可以防止在我的存储库中创建和删除文件。

Thank you in advance.先感谢您。

Another fast question:另一个快速的问题:

Are the words "bytes stream" correct? “字节流”这个词是否正确? or what is the difference?或者有什么区别? what would be the correct words that I am looking for?我正在寻找的正确单词是什么?

So as Balmy mentioned in the comments, the solution is using:因此,正如 Balmy 在评论中提到的那样,解决方案是使用:

ET.tostring()

My code at the end looked something like this:最后我的代码看起来像这样:

# Here you build your xml
x = ET.Element("ExampleXML",{"a tag": "1", "another tag": "2"})

# Here I am saving it to my db by using the "tostring" function, 
# Which as default return the xml as a bytes stream string.
write_to_db("File name", ET.tostring(x))

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

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