我想解析一个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文件列出了项目中使用的每个文件,每个文件都在每个配置中,除非在文件名下面,配置在排除的标签内
我想要实现的是一个功能:
我已成功检索到每个文件,这是我的代码:
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")
如果当前配置排除此文件,我不知道如何继续检查每个文件。
我不太清楚你真正想要做什么,但也许这个片段可以帮到你
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")