你可以给我举几个关于 ET.fromstring 使用的例子么?
时间: 2024-06-10 19:04:39 浏览: 6
当然可以。以下是几个关于 ET.fromstring 的使用例子:
1. 从字符串解析 XML
```
import xml.etree.ElementTree as ET
xml_string = '<person><name>John</name><age>30</age></person>'
root = ET.fromstring(xml_string)
print(root.tag) # Output: person
```
2. 从文件解析 XML
```
import xml.etree.ElementTree as ET
tree = ET.parse('file.xml')
root = tree.getroot()
print(root.tag) # Output: root
```
3. 使用命名空间解析 XML
```
import xml.etree.ElementTree as ET
xml_string = '<root xmlns="https://www.example.com"><child>Hello</child></root>'
root = ET.fromstring(xml_string)
ns = {'ns': 'https://www.example.com'}
child = root.find('ns:child', ns)
print(child.text) # Output: Hello
```
相关问题
那如果使用ET.fromstring呢
`ET.fromstring()`函数可以将字符串格式的XML转换为`Element`对象,如果想要打印出`Element`对象,可以使用`ET.dump()`函数。以下是示例代码:
```python
import xml.etree.ElementTree as ET
# 定义XML字符串
xml_str = "<root><person><name>John</name><age>25</age></person></root>"
# 将XML字符串转换为Element对象
xml_element = ET.fromstring(xml_str)
# 打印Element对象
ET.dump(xml_element)
```
输出结果为:
```
<root>
<person>
<name>John</name>
<age>25</age>
</person>
</root>
```
ET.fromstring对xml转换后,如何打印出来
使用`ET.tostring()`函数,可以将XML转换为字符串格式,然后使用`print()`函数打印出来。以下是示例代码:
```python
import xml.etree.ElementTree as ET
# 定义XML字符串
xml_str = "<root><person><name>John</name><age>25</age></person></root>"
# 将XML字符串转换为Element对象
xml_element = ET.fromstring(xml_str)
# 将Element对象转换为字符串格式
xml_string = ET.tostring(xml_element, encoding="unicode")
# 打印XML字符串
print(xml_string)
```
输出结果为:
```
<root><person><name>John</name><age>25</age></person></root>
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![](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)