Repository navigation
Support indentation of generated xml / html #446
Description
Activity
By analogy with JSON, I'm interested in taking something like this:
{"user":{"id":1,"name":"John Doe","contact":{"email":"[email protected]","phone":{"home":"555-555-5555","work":"555-555-5556"}},"address":{"street":"123 Main St","city":"Anytown","state":"CA","postalCode":"12345","coordinates":{"latitude":37.7749,"longitude":-122.4194}},"preferences":{"notifications":{"email":true,"sms":false},"theme":"dark"}}}and prettifying it like this:
json |> jsonlite::prettify() #> { #> "user": { #> "id": 1, #> "name": "John Doe", #> "contact": { #> "email": "[email protected]", #> "phone": { #> "home": "555-555-5555", #> "work": "555-555-5556" #> } #> }, #> "address": { #> "street": "123 Main St", #> "city": "Anytown", #> "state": "CA", #> "postalCode": "12345", #> "coordinates": { #> "latitude": 37.7749, #> "longitude": -122.4194 #> } #> }, #> "preferences": { #> "notifications": { #> "email": true, #> "sms": false #> }, #> "theme": "dark" #> } #> } #> } #>
But with HTML.
Seemingly, we already do this by default by enabling
NOBLANKSin the reader andformatin the writer options. And indeed sometimes it works:read_xml('<html><head><title>Yolo</title></head></html>') |> write_xml('output.xml') readBin('output.xml', raw(), 1e6) |> rawToChar() |> cat()
However more often it only adds linebreaks, but not indentation but maybe this is to be expected. I think part of the issue is that whitespace in XML is not ignorable. The libxml2 FAQ says:
Libxml2 will not invent spaces in the content of a document since all spaces in the content of a document are significant.
For example, if an xml node contains some code syntax, adding spaces in front can change the code (python for sure 🙄 ) .
But also note that for example html code
<span>Foo</span><b>bar<b>changes meaning when we add whitespace between the nodes because this will become an actual space in the html output try it.
libxml2supports indentation of generated XML / HTML documents, via https://github.com/GNOME/libxml2/blob/master/xmlwriter.c#L4570-L4589. It would be handy if this could be made available inwrite_xml()andwrite_html().