Replacing specific strings in HTML file

I need to translate some of HTML page content. I have a lot of HTML documents as a list of files and a map with translations like this:

List<File> files
Map<String, String> translations

Only strings in specific tags (p, h1..h6, li) have to be translated. I want to end up with the same files like at the beginning but with replaced strings.

Two solutions that don't work:

  1. Replacing - because I don't want to translate strings inside comments or in javascript, another problem is that one string with original text can be a part of another string with original text.
  2. Parsing libraries like Jsoup - because it cleans, fixes dom structure and I want to have unmodified HTML structure.

Any solutions?

Answers


You pretty much have to use a proper html parser (which fixes the dom structure), because otherwise there's no way to tell where an element starts and where it ends. There are all sorts of special cases and different types of broken html and if you want to handle them all, you are basically implementing a full html parser.

The only other way I can think of (and which is often used) is to use placeholders in the original files, such as <h1>${title}</h1> <p>${introduction}</p> etc, and find and replace them directly, but I guess that would require a lot of work to change the files if you don't already have them in this form.


Need Your Help

Best practice for PHP paths

php path twig relative absolute

I have been all over the internet trying to figure out the best way to handle paths in my website. Should I use relative paths, absolute paths?

Extract image url from HTML code using Javascript

javascript

I am pulling information from a Page note from the Facebook API. In the output I get an image URL embeded in HTML code. How can I extract the image url from the HTML code below using Javascript?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.