Skip to content

Instantly share code, notes, and snippets.

@har07
Created April 30, 2015 05:52
Show Gist options
  • Save har07/3bc408a0c1ace6cb5f23 to your computer and use it in GitHub Desktop.
Save har07/3bc408a0c1ace6cb5f23 to your computer and use it in GitHub Desktop.
xml = """<Create>
<SubNetwork networkType="GSM" userLabel="BSC">
</SubNetwork>
<SubNetwork networkType="WCDMA" userLabel="RNC01">
</SubNetwork>
<SubNetwork networkType="IPRAN" userLabel="IPRAN">
</SubNetwork>
<SubNetwork networkType="WCDMA" userLabel="RNC02">
<ManagedElement sourceType="CELLO">
<ManagedElementId string="3GALPAS" />
<primaryType type="RBS" />
.
.
</ManagedElement>
<ManagedElement sourceType="CELLO">
<ManagedElementId string="3GTUTI" />
<primaryType type="RBS" />
.
.
</ManagedElement>
<ManagedElement sourceType="CELLO">
<ManagedElementId string="3GHHH" />
<primaryType type="RBS" />
.
.
</ManagedElement>
</SubNetwork>
</Create>"""
import xml.etree.ElementTree as ET
identifiers = ["3GALPAS","3GTUTI"]
tree = ET.fromstring(xml)
for line in identifiers:
line = line.rstrip()
#get all subnet nodes containing certain ManagedElementId
subnet_path = ".//ManagedElementId[@string='{0}']/../.."
subnet_path = subnet_path.format(line)
for subnet in tree.findall(subnet_path):
#reconstruct subnet node:
parent = ET.Element(subnet.tag, attrib=subnet.attrib)
#xpath to find all ManagedElement containing certain ManagedElementId
content_path = ".//ManagedElementId[@string='{0}']/..".format(line)
#append all ManagedElement found to the new subnet:
for content in subnet.findall(content_path):
parent.append(content)
#print new subnet:
print ET.tostring(parent)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment