XML Modification - hqzhang/cloudtestbed GitHub Wiki

#!/usr/bin/python
# import module
from lxml import etree
# input xml file
parser = etree.XMLParser(remove_blank_text=True)
tree = etree.parse("my.xml",parser)
roots = tree.getroot()

# for scan all nodes(donot care namespace)
for var in roots:
    print root.index(var), var.tag,var.text
    for war in var:
       print root.index(war), war.tag,war.text

# xpath search node name (need care namespace)
node = tree.xpath('/Node/Item/Name')[0]
node = tree.xpath('/ns:Node/ns:Item/ns:Name',namespace=map )[0]

# get and set
node = tree.xpath('/Node/Item/Name')[0]
print node.text
node.text=value

# create node
 product = '''
            <ProductSection mfusion-required="false">
                <Info>CoreOS Virtual Appliance</Info>
            </ProductSection> 
            '''
 product_entry = etree.fromstring(product)

# create and add node1
node = etree.Element('Product')
node.text=val
peer.addnext(node) 

# create and add node2
node = etree.SubElement(parent, "field1")
node.text=val

# insert information
parent.insert(2, product_entry)

# writeback
tree.write('output.xml')

*************
# json operation
# load a file
with open('my.json', 'r') as file:
    cfg = json.load(jsonfile)

# get and set data
print cfg["Node"]["Item"]["Name"]
cfg["Node"]["Item"]["Name"]="Zhang"

# add information into dictory{}
data={"Item99": {"Name": "Hello",  "Date": "2014-01-01","Hero": "1"    } }
node=cfg["Node"]
node.update(data)

# add information into list[]
cfg.append(node)
# add information into tuples():impossible
# write back
with open('output.json', 'w') as file:
          file.write(filedata)

⚠️ **GitHub.com Fallback** ⚠️