python xml 查询
时间: 2023-10-27 21:13:16 浏览: 34
在 Python 中查询 XML 可以使用 ElementTree 模块。下面是一个简单的示例:
首先,假设你有以下的 XML 文件:
```xml
<?xml version="1.0"?>
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications
with XML.</description>
</book>
<book id="bk102">
<author>Ralls, Kim</author>
<title>Midnight Rain</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-12-16</publish_date>
<description>A former architect battles corporate zombies,
an evil sorceress, and her own childhood to become queen
of the world.</description>
</book>
</catalog>
```
然后,你可以使用 ElementTree 模块来打开文件并查询 XML,例如:
```python
import xml.etree.ElementTree as ET
tree = ET.parse('catalog.xml')
root = tree.getroot()
# 查询所有 book 元素
for book in root.findall('book'):
# 获取 book 元素的 id 属性
id = book.get('id')
# 获取 book 元素下的 author 元素的文本内容
author = book.find('author').text
# 获取 book 元素下的 title 元素的文本内容
title = book.find('title').text
# 获取 book 元素下的 price 元素的文本内容
price = book.find('price').text
# 打印查询结果
print(f"Book id: {id}, author: {author}, title: {title}, price: {price}")
```
这个示例将会输出:
```
Book id: bk101, author: Gambardella, Matthew, title: XML Developer's Guide, price: 44.95
Book id: bk102, author: Ralls, Kim, title: Midnight Rain, price: 5.95
```
你也可以使用 XPath 表达式来查询 XML,例如:
```python
# 查询所有 genre 为 Computer 的 book 元素
for book in root.findall("./book[genre='Computer']"):
id = book.get('id')
author = book.find('author').text
title = book.find('title').text
price = book.find('price').text
print(f"Book id: {id}, author: {author}, title: {title}, price: {price}")
```
这个示例将会输出:
```
Book id: bk101, author: Gambardella, Matthew, title: XML Developer's Guide, price: 44.95
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)