在我看到的BeautifulSoup的所有示例和教程中,都传递了HTML /
XML文档,并返回了汤对象,然后可以使用该对象来修改文档。但是,如何使用BeautifulSoup从头开始创建HTML /
XML文档?换句话说,我有要放入XML文件中的数据,但是XML文件尚不存在,我想从头开始构建它。我该怎么办?
只需创建一个空BeautifulSoup()
对象:
soup = BeautifulSoup()
并开始添加元素:
soup.append(soup.new_tag("a", href="http://www.example.com"))
对于XML,可以使用xml
树构建器以XML标头开始:
soup = BeautifulSoup(features='xml')
这要求首先安装lxml。这将在对象.is_xml
上设置标志BeautifulSoup
(也可以手动设置)。
我对如何做到这一点有点困惑,所有的文档/示例都展示了如何读取和编辑xml文档,但似乎没有任何从头开始创建xml的明确方法,我宁愿不必将我的程序与虚拟xml文件一起发布以编辑一个。有什么想法吗?谢谢。
例子 (Demo Example) 这是我们需要创建的XML - <?xml version = "1.0" encoding = "UTF-8"?> <cars> <supercars company = "Ferrari"> <carname type = "formula one">Ferrari 101</carname> <carname type = "s
XPath parser is used to navigate XML Documents only. It is better to use DOM parser for creating XML. Please refer the Java DOM Parser section for the same.
例子 (Demo Example) 这是我们需要创建的XML - <?xml version = "1.0" encoding = "UTF-8" standalone = "no"?> <cars> <supercars company = "Ferrari"> <carname type = "formula one">Ferrari 101</carname>
例子 (Demo Example) 这是我们需要创建的XML文件 - <?xml version = "1.0" encoding = "UTF-8"?> <cars> <supercars company = "Ferrari"> <carname type = "formula one">Ferrari 101</carname> <carname type =
It is better to use StAX parser for creating XML documents rather than using SAX parser. Please refer the Java StAX Parser section for the same.