Say I have the following reST input:
Some text ...
:foo: bar
Some text ...
What I would like to end up with is a dict like this:
{"foo": "bar"}
I tried to use this:
tree = docutils.core.publish_parts(text)
It does parse the field list, but I end up with some pseudo XML in tree["whole"]?
:
<document source="<string>">
<docinfo>
<field>
<field_name>
foo
<field_body>
<paragraph>
bar
Since the tree
dict does not contain any other useful information and that is just a string, I am not sure how to parse the field list out of the reST document. How would I do that?
You can try to use something like the following code. Rather than using the
publish_parts
method I have usedpublish_doctree
, to get the pseudo-XML representation of your document. I have then converted to an XML DOM in order to extract all thefield
elements. Then I get the firstfield_name
andfield_body
elements of eachfield
element.The xml.dom module isn't the easiest to work with (why do I need to use
.firstChild.nodeValue
rather than just.nodeValue
for example), so you may wish to use the xml.etree.ElementTree module, which I find a lot easier to work with. If you use lxml you can also use XPATH notation to find all of thefield
,field_name
andfield_body
elements.Here's my ElementTree implementation:
Usage
I have an alternative solution that I find to be less of a burden, but maybe more brittle. After reviewing the implementation of the node class https://sourceforge.net/p/docutils/code/HEAD/tree/trunk/docutils/docutils/nodes.py you will see that it supports a walk method that can be used to pull out the wanted data without having to create two different xml representations of your data. Here is what I am using now, in my protoype code:
https://github.com/h4ck3rm1k3/gcc-introspector/blob/master/peewee_adaptor.py#L33
and then