Извините, если это основной вопрос, но я застрял на нем некоторое время и не нашел документацию по мини-чертежу, которая понятна. У меня есть этот XML-файл:Python - xml синтаксический разбор с Minidom - Как пронумеровать каждый <parent> и получить список <child> за это <parent>?
<?xml version="1.0"?>
<targetConfiguration>
<virtualMachine>
<boxNameUppercase>CENTOS65</boxNameUppercase>
<boxNameLowercase>centos65</boxNameLowercase>
<memoryMegabytes>2048</memoryMegabytes>
<numCPUs>2</numCPUs>
<installLocation>/home/user/VM_deployer_vms/CENTOS65_Auto/</installLocation>
<diskSpaceGigabytes>10</diskSpaceGigabytes>
<Vagrantfile>/Vagrantfiles/Vagrantfile.centos65.overwritable</Vagrantfile>
<fileToBeSent>
<source>yaml file on system</source>
<destination>bamboo agent location</destination>
</fileToBeSent>
<fileToBeSent>
<source>yaml file on system</source>
<destination>bamboo agent location</destination>
</fileToBeSent>
<scriptToBeRanPython>
<paramaters>-autodetectOS -noPrompt -name</paramaters>
<sourceName>......agent_install.py </sourceName>
<destinationName>SOME LOCATION ON THE MACHINE</destinationName>
</scriptToBeRanPython>
</virtualMachine>
<virtualMachine>
<boxNameUppercase>CENTOS64</boxNameUppercase>
<boxNameLowercase>centos64</boxNameLowercase>
<memoryMegabytes>2048</memoryMegabytes>
<numCPUs>2</numCPUs>
<installLocation>/home/user/VM_deployer_vms/CENTOS64_Auto/</installLocation>
<diskSpaceGigabytes>10</diskSpaceGigabytes>
<Vagrantfile>/Vagrantfiles/Vagrantfile.centos65.overwritable</Vagrantfile>
<fileToBeSent>
<source>yaml file on system</source>
<destination>bamboo agent location</destination>
</fileToBeSent>
<fileToBeSent>
<source>yaml file on system</source>
<destination>bamboo agent location</destination>
</fileToBeSent>
<scriptToBeRanPython>
<paramaters>-autodetectOS -noPrompt -name</paramaters>
<sourceName>......agent_install.py </sourceName>
<destinationName>SOME LOCATION ON THE MACHINE</destinationName>
</scriptToBeRanPython>
</virtualMachine>
</targetConfiguration>
Любая моя проблема заключается в основном с «fileToBeSent» и узлов «scriptToBeRanPython». В моей программе я перебираю каждый узел «virtualMachine» и создаю на нем объект python под названием TargetVM. Я хочу в основном создать список объектов «fileToBeSent» и «scriptToBeRanPython»/tuples и сделать это атрибутом моего класса TargetVM.
Это метод, который вызывается из конструктора в TargetVM, который анализирует остальную часть XML:
def buildConfiguration(self, inputFile):
doc = minidom.parse(inputFile)
#virtualMachine
vm_xml_elements = doc.getElementsByTagName("virtualMachine")
for vm in vm_xml_elements:
myTargetVM=TargetVM()
#mandatory xml nodes
try:
myTargetVM.diskSpaceGigabytes = vm.getElementsByTagName("diskSpaceGigabytes")[0].firstChild.nodeValue
myTargetVM.installLocation = vm.getElementsByTagName("installLocation")[0].firstChild.nodeValue
myTargetVM.vagrantfile = vm.getElementsByTagName("Vagrantfile")[0].firstChild.nodeValue
except:
addFailure("XML error for virtualMachine. You've left out some mandatory tags. ")
#optional xml nodes
try:
myTargetVM.boxNameUppercase = vm.getElementsByTagName("boxNameUppercase")[0].firstChild.nodeValue
myTargetVM.boxNameLowercase= vm.getElementsByTagName("boxNameLowercase")[0].firstChild.nodeValue
myTargetVM.memoryMegabytes = vm.getElementsByTagName("memoryMegabytes")[0].firstChild.nodeValue
myTargetVM.numCPUs = vm.getElementsByTagName("numCPUs")[0].firstChild.nodeValue
except:
addWarning("You left out some optional XML tags when specifying a vagrantBox.")
self.TargetVMList.append(myTargetVM)
Как изменить это, чтобы заставить его работать с выше XML? Я попытался добавить что-то вроде:
printDebug(" Adding commands to "+ VM.getBoxName())
commandsTagList = vm.getElementsByTagName("virtualMachine")
for command in commandsTagList:
commandString = command.getElementsByTagName("scriptToBeRanPython")[0].firstChild.nodeValue
myTargetVM.commandList.append(commandString)
printDebug(" added command '" + commandString + "' to "+VM.getBoxName())
но он возвращает пустой список. Может кто-нибудь мне помочь? Огромное спасибо.
Привет Винод, большое спасибо за ответ :) Мне было интересно, если порядок узлов, getElementsByTagName можно положиться, чтобы быть то же, что и файл XML? Из того, что я понимаю, может, но мне было интересно, есть ли у вас какое-то мнение? Я думал о замене «scriptToBeRanPython» на «commandToBeRun» или что-то еще, и, очевидно, важно, чтобы это было сделано в правильном порядке. – OnMyWayToGodDontKnow
Я не уверен, правильно ли понял ваш вопрос. Все, что я могу сказать, порядок важен. –
Не беспокойтесь, спасибо! – OnMyWayToGodDontKnow