【问题标题】:python: parsing xml file with xmlns without classpython:用没有类的xmlns解析xml文件
【发布时间】:2018-10-24 11:58:44
【问题描述】:

以下是 XML 文件:

<Schedule xmlns="http://xmlns.xyz.com/fal/downtimeschedule/V1.0">
 <Downtime end="20181020000" id="10001197610_20181027000_201810000" mode="cold" start="20181020000"/>
 <PODS>
  <POD DC="US - Washing" deferUpgrade="true" name="ABCD" patching="Production" EndTime="20181028040000">
   <CR id="12345"/>
   <CR id="12346"/>
   <CR id="123"/>
  </POD>
  <POD DC="US - Washing" deferUpgrade="true" name="ABCD-TEST" patching="Production" EndTime="20181028040000">
   <CR id="12345"/>
   <CR id="12346"/>
   <CR id="123"/>
  </POD>
 </PODS>

我想在带有列的 csv 文件中提供输出

1> POD(name)
2> POD(DC)
3> POD(deferUpgrade)

有人可以帮忙吗?是否可以像我在生产环境中那样使用库 xml.etree.ElementTree。

下面是代码。

#!/usr/bin/python
import os
import pandas as pd
import requests
import xml.etree.ElementTree as ET

tree = ET.parse('schedule.xml')

root = tree.getroot()

print root
print root.findall('PODS')
for pods in root.iter('Schedule'):
 for pod in pods.iter('POD'):
    print pod.get('name')

输出:

<Element '{http://xmlns.oracle.com/falcm/flo/downtimeschedule/V1.0}Schedule' at 0x2ae6ed0>
[]

【问题讨论】:

  • 您自己尝试过什么来解决您的任务吗?如果是这样,您能否发布您正在努力的代码。我们很乐意提供帮助,但如果有一些我们可以努力的迹象,而不是我们为 SO 上出现的每一个问题创建东西,那就太好了 :) xml.etree.ElementTree 有关于这个的文档,所以是的,这是一个好的开始。
  • 你可以使用xml.dom并导入minidom

标签: python xml parsing


【解决方案1】:
from xml.dom import minidom

def parseXml(filePath):

    xmldoc = minidom.parse(filePath)
    PODs= xmldoc.getElementsByTagName("POD")
    name=[]
    DC=[]
    deferUpgrade=[]
    for pod in PODs:
        if pod.hasAttribute("name") and pod.hasAttribute("DC") and pod.hasAttribute("deferUpgrade"):
            name.append(pod.getAttribute("name"))
            DC.append(pod.getAttribute("DC"))
            deferUpgrade.append(pod.getAttribute("deferUpgrade"))
    return(name,DC,deferUpgrade)

您可以使用 name,DC,deferUpgrade 来制作您的 CSV 文件

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-15
    • 1970-01-01
    • 2014-07-16
    • 2020-05-30
    相关资源
    最近更新 更多