python - 使用 Python 解析 XML 属性
问题描述
我正在尝试解析所有绿色突出显示的属性(一些敏感的东西已被涂黑),我有一堆格式相似的 XML 文件,我已经知道如何逐个循环它们我在解析时遇到问题不过具体的属性。
我需要属性中的文本:name="text1"
从
project logLevel="verbose" version="2.0" mainModule="Main" name="text1">
destinationDir="/text2"
从
put label="Put Files" destinationDir="/Trigger/FPDMMT_INBOUND">
destDir="/text3"
从
copy disabled="false" version="1.0" label="Archive Files" destDir="/text3" suffix="">
我在用
import csv
import os
import re
import xml.etree.ElementTree as ET
tree = ET.parse(XMLfile_path)
item = tree.getroot()[0]
root = tree.getroot()
print (item.get("name"))
print (root.get("name"))
这输出:
Main
text1
item.get 拉取索引 [0] 处的行,这是树中的第一行根,即 <module root.get 从第一行拉取 <project
我知道有一种方法可以准确地搜索根/树的正确部分,例如:
test = root.find('./project/module/ftp/put')
print (test.get("destinationDir"))
我需要能够直接跳转到我需要的东西并输出我需要的属性。
任何帮助,将不胜感激
谢谢。
解决方案
您的 XML 的简化副本:
xml = '''<project logLevel="verbose" version="2.0" mainModule="Main" name="hidden">
<module name="Main">
<createWorkspace version="1.0"/>
<ftp version="1.0" label="FTP connection to PRD">
<put label="Put Files" destinationDir="destination1">
</put>
</ftp>
<ftp version="1.0" label="FTP connection to PRD">
<put label="Put Files" destinationDir="destination2">
</put>
</ftp>
<copy disabled="false" destDir="destination3">
</copy>
</module>
</project>
'''
# solution using ETree
from xml.etree import ElementTree as ET
root = ET.fromstring(xml)
name = root.get('name')
ftp_destination_dir1 = root.findall('./module/ftp/put')[0].get('destinationDir')
ftp_destination_dir2 = root.findall('./module/ftp/put')[1].get('destinationDir')
copy_destination_dir = root.find('./module/copy').get('destDir')
print(name)
print(ftp_destination_dir1)
print(ftp_destination_dir2)
print(copy_destination_dir)
# solution using lxml
from lxml import etree as et
root = et.fromstring(xml)
name = root.get('name')
ftp_destination_dirs = root.xpath('./module/ftp/put/@destinationDir')
copy_destination_dir = root.xpath('./module/copy/@destDir')[0]
print(name)
print(ftp_destination_dirs[0])
print(ftp_destination_dirs[1])
print(copy_destination_dir)
推荐阅读
- javascript - 为什么我在引导程序中没有得到想要的导航栏?
- python-3.x - 如何在熊猫中将日历年转换为水年
- jquery - 如何使用按钮切换从数组中添加/删除对象?
- python - 在熊猫的一列中减去时间
- reactjs - 异步函数自动返回
- java - Idea 说“未配置 JavaFX 运行时。要么使用内置 JavaFX 的 JDK,要么将 JavaFX 库添加到类路径中”
- c++ - 如何编写代码以在 C++ 中进行条件模板实例化
- javascript - 如何自动触发嵌入站点内的按钮?
- android - CoordinatorLayout - 朝相反方向甩动会导致抖动
- python - Visual Studio Code 中的 Pylint 抱怨导入“sh”模块