Created
September 2, 2019 18:04
-
-
Save msoranno/8a24a5153da75515083167ace39f46e5 to your computer and use it in GitHub Desktop.
Python script to parse xml ovf files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import xml.etree.ElementTree as ET | |
def itemNumber(search_item_text): | |
count = 0 | |
count2 = 0 | |
print('searching:', search_item_text) | |
for var in root.findall('a:VirtualSystem/b:VirtualHardwareSection', ns): | |
#print(var.tag, var.text) | |
for desc in var.findall('c:Item/d:Description', ns): | |
count = count + 1 | |
if desc.text == search_item_text: | |
print('found in count:', count) | |
count2 = count | |
return count2 | |
def register_all_namespaces(filename): | |
# | |
# This method will preserv all namespaces and must be called before write | |
# source: https://stackoverflow.com/questions/54439309/how-to-preserve-namespaces-when-parsing-xml-via-elementtree-in-python | |
# | |
namespaces = dict([node for _, node in ET.iterparse(filename, events=['start-ns'])]) | |
for ns in namespaces: | |
ET.register_namespace(ns, namespaces[ns]) | |
def replaceItem(replace_item, new_value): | |
item_number = str(itemNumber(replace_item)) | |
search_str = ".//a:VirtualSystem/b:VirtualHardwareSection/c:Item[" + item_number + "]/d:VirtualQuantity" | |
current_value = root.find(search_str, ns) | |
if current_value.text == new_value : | |
print('Info: Nothing to do. Current and New are the same') | |
print ('current value:' , current_value.text, ' -- new value:', new_value) | |
else: | |
current_value.text = new_value | |
register_all_namespaces(sourceFile) | |
tree.write(targetFile) | |
# checking on target file | |
tree2 = ET.parse(targetFile) | |
root2 = tree2.getroot() | |
current_value2 = root2.find(search_str, ns) | |
if current_value2.text == new_value: | |
print(replace_item, '.. replaced ok') | |
else: | |
print("Error: this is not good") | |
# ------ | |
# main | |
# ------ | |
sourceFile = "desc.ovf" | |
targetFile = "otro.xml" | |
tree = ET.parse(sourceFile) | |
root = tree.getroot() | |
#for var in root.findall('./{http://schemas.dmtf.org/ovf/envelope/1}VirtualSystem/{http://schemas.dmtf.org/ovf/envelope/1}VirtualHardwareSection/{http://schemas.dmtf.org/ovf/envelope/1}Item/{http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData}VirtualQuantity'): | |
ns = {'a':'http://schemas.dmtf.org/ovf/envelope/1' , | |
'b': 'http://schemas.dmtf.org/ovf/envelope/1' , | |
'c': 'http://schemas.dmtf.org/ovf/envelope/1', | |
'd': 'http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData'} | |
replaceItem('Memory Size', '8192') | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment