首页 > 编程 > Python > 正文

Python对XML进行操作

2019-11-11 02:35:49
字体:
来源:转载
供稿:网友

1.构建xml文件

# -*- coding: utf-8 -*-import xml.etree.ElementTree as ETroot = ET.Element("html")head = ET.SubElement(root, "head")title = ET.SubElement(head, "title")title.text = "Title"body = ET.SubElement(root, "body")body.set("bgcolor", "#ffffff")body.text = "Hello, World!"tree = ET.ElementTree(root)tree.write("hello.xhtml")

hello.xhtml:

<html><head><title>Title</title></head><body bgcolor="#ffffff">Hello, World!</body></html>

2.加载xml文件

# -*- coding: utf-8 -*-import xml.etree.ElementTree as ETtree = ET.parse("hello.xhtml")PRint tree.findtext("head/title")root = tree.getroot()# do something heretree.write("out.xml")

输出:

Title

out.xml:

<html><head><title>Title</title></head><body bgcolor="#ffffff">Hello, World!</body></html>
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表