解析XML文件以根据子元素检索父项

问题描述 投票:1回答:1

我想解析一个xml文件,这是我的xml文件:

<group>
  <name>Services</name>
  <file>
    <name>Path\File1.c</name>
  </file>
  <file>
    <name>Path\File2.c</name>
    <excluded>
      <configuration>Configuration1</configuration>
      <configuration>Configuration2</configuration>
    </excluded>
  </file>
  <file>
    <name>Path\File3.c</name>
    <excluded>
      <configuration>Configuration2</configuration>
      <configuration>Configuration3</configuration>
    </excluded>
  </file>
  <file>
    <name>Path\File4.c</name>
  </file>
</group>

此xml文件描述了项目中使用的文件。此项目具有多个配置,名为Configuration1到Configuration4。对于该示例,我们假设我可以访问这些,这要归功于配置名称列表。 xml文件列出了项目中使用的每个文件,每个文件都在每个配置中,除非在文件名下面,配置在排除的标签内

我想要实现的是一个功能:

  • 给定xml树,配置名称将返回此配置中使用的所有文件的列表。

我已成功检索到每个文件,这是我的代码:

from lxml import etree

def getSourceFile(sTree, szConfigName):
  #retrieve every file used in the project
  lSource = []
  for data in sTree.xpath('/group'):
      file = data.findall("file")
      for x in file:
        for element in x:
          if(element.tag == "name"):          
              lSource.append(element.text)
  print(lSource)

if __name__ == '__main__':
  sTree = etree.parse("myXmlFile.xml")
  lConfigName = ["Configuration1", "Configuration2", "Configuration3", "Configuration4"]

  for iIdxConfig in range(0, len(lConfigName)):
    getSourceFile(sTree, lConfigName[iIdxConfig])
    print("\n\n")

如果当前配置排除此文件,我不知道如何继续检查每个文件。

python xml-parsing
1个回答
1
投票

我不太清楚你真正想要做什么,但也许这个片段可以帮到你

from lxml import etree

def getSourceFile(sTree, szConfigName):
#retrieve every file used in the project
lSource = []
for data in sTree.xpath('/group'):
  file = data.findall("file")
  for x in file:
    myName = ""
    confIsExcluded=False
    for element in x:
      if(element.tag == "name"):
        myName = element.text
      if(element.tag == "excluded"):
        configurations = [config.text for config in element.findall("configuration")]
        if(szConfigName in configurations):
          confIsExcluded=True
    if(not confIsExcluded):
      lSource.append(myName)
print(lSource)

if __name__ == '__main__':
  sTree = etree.parse("myXmlFile.xml")
  lConfigName = ["Configuration1", "Configuration1", "Configuration2", "Configuration3"]

  for iIdxConfig in range(0, len(lConfigName)):
  getSourceFile(sTree, lConfigName[iIdxConfig])
  print("\n\n")
© www.soinside.com 2019 - 2024. All rights reserved.