code_junkie

Best XML writing tool for Python

Nov 10th, 2011
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.35 KB | None | 0 0
  1. import xml.etree.ElementTree as ET
  2. root = ET.Element('html')
  3. head = ET.SubElement(root,'head')
  4. script = ET.SubElement(head,'script')
  5. script.set('type','text/javascript')
  6. script.text = "var a = 'I love á letters'"
  7. body = ET.SubElement(root,'body')
  8. h1 = ET.SubElement(body,'h1')
  9. h1.text = "And I like the fact that 3 > 1"
  10. tree = ET.ElementTree(root)
  11. tree.write('foo.xhtml')
  12.  
  13. # more foo.xhtml
  14. <html><head><script type="text/javascript">var a = 'I love &aacute;
  15. letters'</script></head><body><h1>And I like the fact that 3 > 1</h1>
  16. </body></html>
  17.  
  18. from xml.dom.minidom import parseString
  19.  
  20. doc = parseString("""<html>
  21. <head>
  22. <script type="text/javascript">
  23. var a = 'I love &aacute; letters'
  24. </script>
  25. </head>
  26. <body>
  27. <h1>And I like the fact that 3 > 1</h1>
  28. </body>
  29. </html>""")
  30.  
  31. with open("foo.xhtml", "w") as f:
  32. f.write( doc.toxml() )
  33.  
  34. var a = '%(message)s'
  35.  
  36. </html>""" % {"message": "I love &aacute; letters"})
  37.  
  38. from elementtree.SimpleXMLWriter import XMLWriter
  39. import sys
  40.  
  41. w = XMLWriter(sys.stdout)
  42. html = w.start("html")
  43.  
  44. w.start("head")
  45. w.element("title", "my document")
  46. w.element("meta", name="generator", value="my application 1.0")
  47. w.end()
  48.  
  49. w.start("body")
  50. w.element("h1", "this is a heading")
  51. w.element("p", "this is a paragraph")
  52.  
  53. w.start("p")
  54. w.data("this is ")
  55. w.element("b", "bold")
  56. w.data(" and ")
  57. w.element("i", "italic")
  58. w.data(".")
  59. w.end("p")
  60.  
  61. w.close(html)
  62.  
  63. >>> from lxml.builder import E
  64.  
  65. >>> def CLASS(*args): # class is a reserved word in Python
  66. ... return {"class":' '.join(args)}
  67.  
  68. >>> html = page = (
  69. ... E.html( # create an Element called "html"
  70. ... E.head(
  71. ... E.title("This is a sample document")
  72. ... ),
  73. ... E.body(
  74. ... E.h1("Hello!", CLASS("title")),
  75. ... E.p("This is a paragraph with ", E.b("bold"), " text in it!"),
  76. ... E.p("This is another paragraph, with a", "n ",
  77. ... E.a("link", href="http://www.python.org"), "."),
  78. ... E.p("Here are some reservered characters: <spam&egg>."),
  79. ... etree.XML("<p>And finally an embedded XHTML fragment.</p>"),
  80. ... )
  81. ... )
  82. ... )
  83.  
  84. >>> print(etree.tostring(page, pretty_print=True))
  85. <html>
  86. <head>
  87. <title>This is a sample document</title>
  88. </head>
  89. <body>
  90. <h1 class="title">Hello!</h1>
  91. <p>This is a paragraph with <b>bold</b> text in it!</p>
  92. <p>This is another paragraph, with a
  93. <a href="http://www.python.org">link</a>.</p>
  94. <p>Here are some reservered characters: <spam&egg>.</p>
  95. <p>And finally an embedded XHTML fragment.</p>
  96. </body>
  97. </html>
  98.  
  99. w = genx.Writer()
  100. w.startDocFile(sys.stdout)
  101. w.startElementLiteral("TopLevelElement")
  102. w.addText("Some Text")
  103. w.endElement()
  104. w.endDocument()
  105.  
  106. from xml.sax import saxutils
  107. from xml.dom.minidom import parseString
  108. from xml.parsers.expat import ExpatError
  109.  
  110. xml = '''<?xml version="1.0" encoding="%s"?>n
  111. <contents title="%s" crawl_date="%s" in_text_date="%s"
  112. url="%s">n<main_post>%s</main_post>n</contents>''' %
  113. (self.encoding, saxutils.escape(title), saxutils.escape(time),
  114. saxutils.escape(date), saxutils.escape(url), saxutils.escape(contents))
  115. try:
  116. minidoc = parseString(xml)
  117. catch ExpatError:
  118. print "Invalid xml"
  119.  
  120. html(head(script(type='text/javascript', content='var a = ...')),
  121. body(h1('And I like the fact that 3 < 1'), p('just some paragraph'))
  122.  
  123. from magictree import html, head, script, body, h1, p
  124. root = html(
  125. head(
  126. script('''var a = 'I love &aacute; letters''',
  127. type='text/javascript')),
  128. body(
  129. h1('And I like the fact that 3 > 1')))
  130.  
  131. # root is a plain Element object, like those created with ET.Element...
  132. # so you can write it out using ElementTree :)
  133. tree = ET.ElementTree(root)
  134. tree.write('foo.xhtml')
  135.  
  136. import xmlwitch
  137. xml = xmlwitch.Builder(version='1.0', encoding='utf-8')
  138. with xml.feed(xmlns='http://www.w3.org/2005/Atom'):
  139. xml.title('Example Feed')
  140. xml.updated('2003-12-13T18:30:02Z')
  141. with xml.author:
  142. xml.name('John Doe')
  143. xml.id('urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6')
  144. with xml.entry:
  145. xml.title('Atom-Powered Robots Run Amok')
  146. xml.id('urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a')
  147. xml.updated('2003-12-13T18:30:02Z')
  148. xml.summary('Some text.')
  149. print(xml)
  150.  
  151. #
  152. #Output the XML entry
  153. #
  154. def genFileOLD(out,label,term,idval):
  155. filename=entryTime() + ".html"
  156. writer=MarkupWriter(out, indent=u"yes")
  157. writer.startDocument()
  158. #Test element and attribute writing
  159. ans=namespace=u'http://www.w3.org/2005/Atom'
  160. xns=namespace=u'http://www.w3.org/1999/xhtml'
  161. writer.startElement(u'entry',
  162. ans,
  163. extraNss={u'x':u'http://www.w3.org/1999/xhtml' ,
  164. u'dc':u'http://purl.org/dc/elements/1.1'})
  165. #u'a':u'http://www.w3.org/2005/Atom',
  166. #writer.attribute(u'xml:lang',unicode("en-UK"))
  167.  
  168. writer.simpleElement(u'title',ans,content=unicode(label))
  169. #writer.simpleElement(u'a:subtitle',ans,content=u' ')
  170. id=unicode("http://www.dpawson.co.uk/nodesets/"+afn.split(".")[0])
  171. writer.simpleElement(u'id',ans,content=id)
  172. writer.simpleElement(u'updated',ans,content=unicode(dtime()))
  173. writer.startElement(u'author',ans)
  174. writer.simpleElement(u'name',ans,content=u'Dave ')
  175. writer.simpleElement(u'uri',ans,
  176. content=u'http://www.dpawson.co.uk/nodesets/'+afn+".xml")
  177. writer.endElement(u'author')
  178. writer.startElement(u'category', ans)
  179. if (prompt):
  180. label=unicode(raw_input("Enter label "))
  181. writer.attribute(u'label',unicode(label))
  182. if (prompt):
  183. term = unicode(raw_input("Enter term to use "))
  184. writer.attribute(u'term', unicode(term))
  185. writer.endElement(u'category')
  186. writer.simpleElement(u'rights',ans,content=u'u00A9 Dave 2005-2008')
  187. writer.startElement(u'link',ans)
  188. writer.attribute(u'href',
  189. unicode("http://www.dpawson.co.uk/nodesets/entries/"+afn+".html"))
  190. writer.attribute(u'rel',unicode("alternate"))
  191. writer.endElement(u'link')
  192. writer.startElement(u'published', ans)
  193. dt=dtime()
  194. dtu=unicode(dt)
  195. writer.text(dtu)
  196. writer.endElement(u'published')
  197. writer.simpleElement(u'summary',ans,content=unicode(label))
  198. writer.startElement(u'content',ans)
  199. writer.attribute(u'type',unicode("xhtml"))
  200. writer.startElement(u'div',xns)
  201. writer.simpleElement(u'h3',xns,content=unicode(label))
  202. writer.endElement(u'div')
  203. writer.endElement(u'content')
  204. writer.endElement(u'entry')
Add Comment
Please, Sign In to add comment