无法使用Python解析XML文件

时间:2018-11-23 15:10:38

标签: python xml

<?xml version="1.0" encoding="utf-8"?>
<AcResponse
    Command="hist"
    TaskId="408709">
  <element
      name="/build.gradle"
      id="93527">
    <transaction
        id="1117194"
        type="promote"
        time="1529083792"
        user="soarfa99">
      <comment>Automated promotion to parent stream by module build: jenkins-SC-MODULE-CS-SC-TRUNK-MedRec-DEV-CI-430</comment>
      <version
          virtual="11007/75"
          real="36877/2"
          virtualNamedVersion="CS-SC-TRUNK-INTG/75"
          realNamedVersion="CS-SC-TRUNK-MedRec-DEV2_ar037601/2"
          elem_type="text"
          dir="no">
        <issueNum>72768</issueNum>
      </version>
    </transaction>
    <transaction
        id="1111652"
        type="promote"
        time="1528100495"
        user="dm041068">
      <comment>SEDA file add- Debajyoti</comment>
      <version
          virtual="11007/74"
          real="39225/1"
          virtualNamedVersion="CS-SC-TRUNK-INTG/74"
          realNamedVersion="CS-SC-TRUNK-CM-DEV-Debajyoti_dm041068/1"
          elem_type="text"
          dir="no">
        <issueNum>72629</issueNum>
      </version>
    </transaction>
  </element>
  <streams>
    <stream
        id="11007"
        name="CS-SC-TRUNK-INTG"
        type="normal"/>
  </streams>
</AcResponse>

这是我正在尝试解析的xml,并且我正在尝试使用以下代码提取属性“ issueNum”:

tree=ET.parse(xml)
root=tree.getroot()
for item in root.findall('version'):
    for child in item:
        print(child.attrib['issueNum'])

请您帮忙,给我“ issueNum”的值。

1 个答案:

答案 0 :(得分:0)

您可以使用xpath expression来查找issueNum的值:

from lxml import etree

xml = '''<?xml version="1.0" encoding="utf-8"?>
<AcResponse
    Command="hist"
    TaskId="408709">....'''

tree = etree.fromstring(xml)
issues = tree.xpath('//version/issueNum')

for issue in issues:
    print(issue.text)

此打印:

72768
72629