python如何获取节点类型
时间: 2023-07-15 20:10:57 浏览: 46
在Python中,可以使用xml.etree.ElementTree模块来解析和操作XML文档。要获取一个节点的类型,可以使用Element对象的tag属性。
例如,假设我们有以下的XML文档:
```xml
<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="children">
<title lang="en">Harry Potter</title>
<author>J.K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
</bookstore>
```
我们可以使用ElementTree模块来解析该文档,并获取节点的类型:
```python
import xml.etree.ElementTree as ET
tree = ET.parse('books.xml')
root = tree.getroot()
for child in root:
print(child.tag) # 输出节点的标签名,即节点类型
```
运行以上代码,输出结果为:
```
book
book
```
因此,我们可以看到,获取节点的类型即是获取节点的标签名。