Skip to content
Advertisement

Java add attribute to HTML tags without changing formatting

A have a task to make a maven plugin which takes HTML files in certain location and adds a service attribute to each tag that doesn’t have it. This is done on the source code which means my colleagues and I will have to edit those files further.

As a first solution I turned to Jsoup which seems to be doing the job but has one small yet annoying problem: if we have a tag with multiple long attributes (we often do as this HTML code is a source for further processing) we wrap the lines like this:

<ui:grid id="category_search" title="${handler.getMessage( 'title' )}" 
        class="is-small is-outlined is-hoverable is-foldable"
        filterListener="onApplyFilter" paginationListener="onPagination" ds="${handler.ds}" 
        filterFragment="grid_filter" contentFragment="grid_contents"/>


However, Jsoup turns this into one very long line:

<ui:grid id="category_search" title="${handler.getMessage( 'title' )}" class="is-small is-outlined is-hoverable is-foldable" filterListener="onApplyFilter" paginationListener="onPagination" ds="${handler.ds}" filterFragment="grid_filter" contentFragment="grid_contents"/>

Which is a bad practice and real pain to read and edit.

So is there any other not very convoluted way to add this attribute without parsing and recomposing HTML code or maybe somehow preserve line breaks inside the tag?

Advertisement

Answer

It seems there is no good way to preserve breaks inside tags while parsing them into POJOs (or I haven’t found one), so I wrote a simple tokenizer which splits incoming HTML string into parts sort of like this:

String[] parts = html.split( "((?=<)|(?<=>))" );

This uses regex lookups to split before < and after >. Then just iterate over parts and decide whether to insert attribute or not.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement