4 ms·
$ cat my-config.xml <root> <!-- i am a comment --> <thing attr="foo"> <!-- i am another comment --> <setting>value</
by _wmd 9y ago
$ cat my-config.xml
<root>
<!-- i am a comment -->
<thing attr="foo">
<!-- i am another comment -->
<setting>value</setting>
</thing>
</root>
$ cat c.py
import lxml.etree
doc = lxml.etree.fromstring(file('my-config.xml').read())
for setting in doc.xpath('.//thing/setting'):
setting.text = 'set without screwing up the file'
print lxml.etree.tostring(doc)
$ python c.py
<root>
<!-- i am a comment -->
<thing attr="foo">
<!-- i am another comment -->
<setting>set without screwing up the file</setting>
</thing>
</root>
- openasocket 9y ago... but you just chewed someone out for suggesting XML. And you are doing tree walking here, you're just reducing some of the boilerplate with XPath. You can do the same thing with Scheme using car, cdr, cadr and friends.
- _wmd 9y agoThe suggestion was to use XSLT to transform Scheme syntax
- openasocket 9y agoMy mistake then. You can still use car, cdr, cadr etc. to accomplish more or less the same thing as XPath. S-expressions are a completely valid serialization format. You can't easily manipulate JSON or YAML data while preserving formatting and comments with any library I've used (though it is possible), that doesn't mean JSON and YAML are invalid.
- mcguire 9y agoXPath and a tree transformation? Works well.