使用dominatedocument()函数在Python中创建DOM类型文档
发布时间:2023-12-26 01:24:54
在Python中,可以使用xml.dom.minidom模块来创建DOM类型的文档。DOM(Document Object Model)是一种表示HTML或XML文档的标准对象模型,它将文档解析成一个树状结构,可以方便地操作和修改文档中的元素。
要创建一个DOM类型的文档,首先需要导入xml.dom.minidom模块:
from xml.dom.minidom import Document
然后,可以创建一个Document对象作为文档的根节点:
doc = Document()
现在,可以向文档中添加元素和属性。例如,创建一个根元素:
root = doc.createElement("root")
doc.appendChild(root)
创建一个子元素并添加到根元素中:
child = doc.createElement("child")
root.appendChild(child)
为子元素添加一个属性:
child.setAttribute("name", "example")
创建一个文本节点并添加到子元素中:
text = doc.createTextNode("This is an example text.")
child.appendChild(text)
最后,可以将文档保存到文件中:
with open("example.xml", "w") as f:
doc.writexml(f, indent="\t", newl="
")
完整的创建DOM类型文档的例子如下:
from xml.dom.minidom import Document
# 创建Document对象
doc = Document()
# 创建根元素
root = doc.createElement("root")
doc.appendChild(root)
# 创建子元素
child = doc.createElement("child")
root.appendChild(child)
# 添加子元素的属性
child.setAttribute("name", "example")
# 创建文本节点
text = doc.createTextNode("This is an example text.")
child.appendChild(text)
# 将文档保存到文件
with open("example.xml", "w") as f:
doc.writexml(f, indent="\t", newl="
")
执行上述代码后,将会创建一个名为example.xml的文件,其内容为以下XML文档:
<root> <child name="example">This is an example text.</child> </root>
这样,我们就成功地使用dom.Document()函数创建了一个DOM类型的文档,并添加了元素和属性。
