code_junkie

Editing XML as a dictionary in python?

Nov 11th, 2011
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.04 KB | None | 0 0
  1. <root>
  2. <level1>leaf1</level1>
  3. <level2>leaf2</level2>
  4. </root>
  5.  
  6. from BeautifulSoup import BeatifulStoneSoup, Tag, NavigableString
  7.  
  8. soup = BeautifulStoneSoup('config-template.xml') # get the parser for the xml file
  9. soup.contents[0].name
  10. # u'root'
  11.  
  12. soup.root.contents[0].name
  13. # u'level1'
  14.  
  15. import re
  16. tags_starting_with_level = soup.findAll(re.compile('^level'))
  17. for tag in tags_starting_with_level: print tag.name
  18. # level1
  19. # level2
  20.  
  21. # build and insert a new level with a new leaf
  22. level3 = Tag(soup, 'level3')
  23. level3.insert(0, NavigableString('leaf3')
  24. soup.root.insert(2, level3)
  25.  
  26. print soup.prettify()
  27. # <root>
  28. # <level1>
  29. # leaf1
  30. # </level1>
  31. # <level2>
  32. # leaf2
  33. # </level2>
  34. # <level3>
  35. # leaf3
  36. # </level3>
  37. # </root>
  38.  
  39. import xml.etree.ElementTree as ET
  40. doc = ET.parse("template.xml")
  41. lvl1 = doc.findall("level1-name")[0]
  42. lvl1.remove(lvl1.find("leaf1")
  43. lvl1.remove(lvl1.find("leaf2")
  44. # or use del lvl1[idx]
  45. doc.write("config-new.xml")
  46.  
  47. import xml.etree.ElementTree as etree
  48.  
  49. tree = etree.parse('test.xml')
  50. root = tree.getroot()
  51.  
  52. def xml_to_dict(el):
  53. d={}
  54. if el.text:
  55. d[el.tag] = el.text
  56. else:
  57. d[el.tag] = {}
  58. children = el.getchildren()
  59. if children:
  60. d[el.tag] = map(xml_to_dict, children)
  61. return d
  62.  
  63. {'note': [{'to': 'Tove'},
  64. {'from': 'Jani'},
  65. {'heading': 'Reminder'},
  66. {'body': "Don't forget me this weekend!"}]}
  67.  
  68. def xml_to_dictionary(element):
  69. l = len(namespace)
  70. dictionary={}
  71. tag = element.tag[l:]
  72. if element.text:
  73. if (element.text == ' '):
  74. dictionary[tag] = {}
  75. else:
  76. dictionary[tag] = element.text
  77. children = element.getchildren()
  78. if children:
  79. subdictionary = {}
  80. for child in children:
  81. for k,v in xml_to_dictionary(child).items():
  82. if k in subdictionary:
  83. if ( isinstance(subdictionary[k], list)):
  84. subdictionary[k].append(v)
  85. else:
  86. subdictionary[k] = [subdictionary[k], v]
  87. else:
  88. subdictionary[k] = v
  89. if (dictionary[tag] == {}):
  90. dictionary[tag] = subdictionary
  91. else:
  92. dictionary[tag] = [dictionary[tag], subdictionary]
  93. if element.attrib:
  94. attribs = {}
  95. for k,v in element.attrib.items():
  96. attribs[k] = v
  97. if (dictionary[tag] == {}):
  98. dictionary[tag] = attribs
  99. else:
  100. dictionary[tag] = [dictionary[tag], attribs]
  101. return dictionary
  102.  
  103. spacepattern = re.compile(r's+')
  104. mydictionary = xml_to_dictionary(ElementTree.XML(spacepattern.sub(' ', content)))
  105.  
  106. {'note': {'to': 'Tove',
  107. 'from': 'Jani',
  108. 'heading': 'Reminder',
  109. 'body': "Don't forget me this weekend!"}}
  110.  
  111. <elementName attributeName='attributeContent'>elementContent</elementName>
  112.  
  113. print xml.etree.ElementTree.tostring( conf_new )
  114.  
  115. root = ET.parse(xh)
  116. data = root.getroot()
  117. xdic = {}
  118. if data > None:
  119. for part in data.getchildren():
  120. xdic[part.tag] = part.text
Add Comment
Please, Sign In to add comment