Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <root>
- <level1>leaf1</level1>
- <level2>leaf2</level2>
- </root>
- from BeautifulSoup import BeatifulStoneSoup, Tag, NavigableString
- soup = BeautifulStoneSoup('config-template.xml') # get the parser for the xml file
- soup.contents[0].name
- # u'root'
- soup.root.contents[0].name
- # u'level1'
- import re
- tags_starting_with_level = soup.findAll(re.compile('^level'))
- for tag in tags_starting_with_level: print tag.name
- # level1
- # level2
- # build and insert a new level with a new leaf
- level3 = Tag(soup, 'level3')
- level3.insert(0, NavigableString('leaf3')
- soup.root.insert(2, level3)
- print soup.prettify()
- # <root>
- # <level1>
- # leaf1
- # </level1>
- # <level2>
- # leaf2
- # </level2>
- # <level3>
- # leaf3
- # </level3>
- # </root>
- import xml.etree.ElementTree as ET
- doc = ET.parse("template.xml")
- lvl1 = doc.findall("level1-name")[0]
- lvl1.remove(lvl1.find("leaf1")
- lvl1.remove(lvl1.find("leaf2")
- # or use del lvl1[idx]
- doc.write("config-new.xml")
- import xml.etree.ElementTree as etree
- tree = etree.parse('test.xml')
- root = tree.getroot()
- def xml_to_dict(el):
- d={}
- if el.text:
- d[el.tag] = el.text
- else:
- d[el.tag] = {}
- children = el.getchildren()
- if children:
- d[el.tag] = map(xml_to_dict, children)
- return d
- {'note': [{'to': 'Tove'},
- {'from': 'Jani'},
- {'heading': 'Reminder'},
- {'body': "Don't forget me this weekend!"}]}
- def xml_to_dictionary(element):
- l = len(namespace)
- dictionary={}
- tag = element.tag[l:]
- if element.text:
- if (element.text == ' '):
- dictionary[tag] = {}
- else:
- dictionary[tag] = element.text
- children = element.getchildren()
- if children:
- subdictionary = {}
- for child in children:
- for k,v in xml_to_dictionary(child).items():
- if k in subdictionary:
- if ( isinstance(subdictionary[k], list)):
- subdictionary[k].append(v)
- else:
- subdictionary[k] = [subdictionary[k], v]
- else:
- subdictionary[k] = v
- if (dictionary[tag] == {}):
- dictionary[tag] = subdictionary
- else:
- dictionary[tag] = [dictionary[tag], subdictionary]
- if element.attrib:
- attribs = {}
- for k,v in element.attrib.items():
- attribs[k] = v
- if (dictionary[tag] == {}):
- dictionary[tag] = attribs
- else:
- dictionary[tag] = [dictionary[tag], attribs]
- return dictionary
- spacepattern = re.compile(r's+')
- mydictionary = xml_to_dictionary(ElementTree.XML(spacepattern.sub(' ', content)))
- {'note': {'to': 'Tove',
- 'from': 'Jani',
- 'heading': 'Reminder',
- 'body': "Don't forget me this weekend!"}}
- <elementName attributeName='attributeContent'>elementContent</elementName>
- print xml.etree.ElementTree.tostring( conf_new )
- root = ET.parse(xh)
- data = root.getroot()
- xdic = {}
- if data > None:
- for part in data.getchildren():
- xdic[part.tag] = part.text
Add Comment
Please, Sign In to add comment