创建具有BeautifulSoup一个XML文档 [英] Creating an XML document with BeautifulSoup
问题描述
在我看到BeautifulSoup的所有实施例和教程,一个HTML / XML文档被传递并返回汤对象然后可用于修改文件。但是,我怎么能使用BeautifulSoup从头开始创建一个HTML / XML文档?换句话说,我有我想放在一个XML文件中的数据,但XML文件并不存在,我想从头开始构建。我如何做呢?
In all the examples and tutorials I have seen of BeautifulSoup, an HTML/XML document is passed and a soup object is returned which can then be used to modify the document. However, how can I use BeautifulSoup to create a HTML/XML document from scratch? In other words, I have data that I would like to put in an XML file, but the XML file does not exist yet and I would like to build it from scratch. How can I go about it?
推荐答案
只是创建一个空的 BeautifulSoup()
对象:
Just create an empty BeautifulSoup()
object:
soup = BeautifulSoup()
和开始添加元素:
soup.append(soup.new_tag("a", href="http://www.example.com"))
有关XML,你可以通过使用 XML
树构建一个XML头开始了:
For XML you could start out with a XML header by using the xml
tree builder:
soup = BeautifulSoup(features='xml')
这需要LXML先安装。这台 BeautifulSoup
对象的 .is_xml
标志(也可手动设置)。
This requires lxml to be installed first. This sets the .is_xml
flag on the BeautifulSoup
object (which can also be set manually).
这篇关于创建具有BeautifulSoup一个XML文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!