怎样把 txt文件转成XML
时间: 2023-11-13 12:40:43 浏览: 99
将txt文件转换为XML文件可以通过编程语言来实现,以下是使用Python语言的示例代码:
```python
import xml.etree.ElementTree as ET
def txt_to_xml(txt_file, xml_file):
# 创建根节点
root = ET.Element("data")
# 读取txt文件内容
with open(txt_file, "r") as file:
lines = file.readlines()
# 遍历每一行文本,生成XML节点
for line in lines:
# 创建子节点
child = ET.SubElement(root, "item")
# 添加文本内容
child.text = line.strip()
# 创建XML树并写入文件
tree = ET.ElementTree(root)
tree.write(xml_file, encoding="utf-8", xml_declaration=True)
# 示例调用
txt_to_xml("input.txt", "output.xml")
```
这段代码将会读取名为"input.txt"的文本文件内容,并将每一行作为XML的子节点,生成名为"output.xml"的XML文件。你需要将"input.txt"和"output.xml"替换为你自己的文件路径。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)