{site_name}

{site_name}

🌜 搜索

Python可以使用内置的XML模块或第三方库,如lxml或ElementTree等来构建XML文档

Python 𝄐 0
python 写xml,python xml dom,python xml.dom.minidom模块生成xml,python3 xml,python xml.etree,python创建xml
Python可以使用内置的XML模块或第三方库,如lxml或ElementTree等来构建XML文档。构建XML文档涉及两个主要概念:元素和属性。

元素是XML文档中的主要部分,它们可以包含其他元素和属性。在Python中,可以使用Element对象来表示元素。可以通过创建一个顶级元素并向其添加子元素和属性来构建XML文档。例如,下面的代码将创建一个名为“book”的顶级元素,并向其添加标题、作者和出版日期等子元素:

python
import xml.etree.ElementTree as ET

root = ET.Element("book")
title = ET.SubElement(root, "title")
title.text = "The Catcher in the Rye"
author = ET.SubElement(root, "author")
author.text = "J.D. Salinger"
published = ET.SubElement(root, "published")
published.text = "1951"

tree = ET.ElementTree(root)
tree.write("book.xml")


上述代码将生成以下XML文档:

xml
<book>
<title>The Catcher in the Rye</title>
<author>J.D. Salinger</author>
<published>1951</published>
</book>


此外,还可以使用set()方法为元素添加属性。例如,可以添加一个名为“id”的属性来表示书籍的唯一标识符:

python
import xml.etree.ElementTree as ET

root = ET.Element("book", {"id": "123"})
title = ET.SubElement(root, "title")
title.text = "The Catcher in the Rye"
author = ET.SubElement(root, "author")
author.text = "J.D. Salinger"
published = ET.SubElement(root, "published")
published.text = "1951"

tree = ET.ElementTree(root)
tree.write("book.xml")


通过添加属性,生成的XML文档现在如下所示:

xml
<book id="123">
<title>The Catcher in the Rye</title>
<author>J.D. Salinger</author>
<published>1951</published>
</book>