首页 > 解决方案 > 使用 Python 解析 XML 属性

问题描述

我正在尝试解析所有绿色突出显示的属性(一些敏感的东西已被涂黑),我有一堆格式相似的 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"))

我需要能够直接跳转到我需要的东西并输出我需要的属性。

任何帮助,将不胜感激

谢谢。

标签: pythonxml

解决方案


您的 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)

推荐阅读