| 1 | = Generating Markup Programmatically = |
| 2 | |
| 3 | Markup provides a `builder` module which lets you generate markup from Python code using a very simple syntax. |
| 4 | |
| 5 | The main entry point to the `builder` module is the `tag` object (which actually is an instance of the `ElementFactory` class). Elements can be created through this `tag` object using attribute access, for example: |
| 6 | |
| 7 | {{{ |
| 8 | #!python |
| 9 | >>> from markup.builder import tag |
| 10 | >>> doc = tag.p('Some text and ', tag.a('a link', href='http://example.org/'), '.') |
| 11 | >>> doc |
| 12 | <Element "p"> |
| 13 | }}} |
| 14 | |
| 15 | This produces an `Element` instance which can be further modified to add child nodes and attributes. It can also be directly rendered to XML text: |
| 16 | |
| 17 | {{{ |
| 18 | #!python |
| 19 | >>> print doc |
| 20 | <p>Some text and <a href="http://example.org/">a link</a>.</p> |
| 21 | }}} |
| 22 | |
| 23 | This is basically a shortcut for converting the `Element` to a [wiki:MarkupStream stream] and rendering the stream: |
| 24 | |
| 25 | {{{ |
| 26 | #!python |
| 27 | >>> stream = doc.generate() |
| 28 | >>> stream |
| 29 | <markup.core.Stream object at 0x72d230> |
| 30 | >>> print stream |
| 31 | <p>Some text and <a href="http://example.org/">a link</a>.</p> |
| 32 | }}} |
| 33 | |
| 34 | The full functionality of streams is available for streams generated this way. For example, sub-streams can be extracted using XPath expressions with the `select()` method: |
| 35 | |
| 36 | {{{ |
| 37 | #!python |
| 38 | >>> substream = stream.select('a') |
| 39 | >>> substream |
| 40 | <markup.core.Stream object at 0x71e090> |
| 41 | >>> print substream |
| 42 | <a href="http://example.org/">a link</a> |
| 43 | }}} |