Generating CSS styles based on an HTML document

I have a file with numerous HTML elements:

<div>
    <div id="imgElt11289447233738dIi15v" style="BORDER-RIGHT: 0px; BORDER-TOP: 0px; Z-INDEX: 1; LEFT: 795px; BORDER-LEFT: 0px; WIDTH: 90px; CURSOR: auto; BORDER-BOTTOM: 0px; POSITION: absolute; TOP: 186px; HEIGHT: 93px" lineid="lineid" y2="279" y1="186" x2="885" x1="795">
        <img style="WIDTH: 90px; HEIGHT: 93px" height="21" alt="Image" src="../images//k03.jpg" width="25" name="imgElt11289447233738dIi15vNI1m6G" tag="img"></img></div>
    <div id="imgElt11288263284216dIi15v" style="BORDER-RIGHT: 0px; BORDER-TOP: 0px; Z-INDEX: 1; LEFT: 660px; BORDER-LEFT: 0px; WIDTH: 147px; CURSOR: auto; BORDER-BOTTOM: 0px; POSITION: absolute; TOP: 1964px; HEIGHT: 22px" lineid="lineid" y2="1986" y1="1964" x2="807" x1="660">
        <img style="WIDTH: 147px; HEIGHT: 22px" height="21" alt="Image" src="../images//k03.jpg" width="25" name="imgElt11288263284216dIi15vNI1m6G" tag="img"></img></div>
    <div id="txtElt11288262779851dIi15v" style="BORDER-RIGHT: 0px; BORDER-TOP: 0px; Z-INDEX: 2872735; LEFT: 250px; BORDER-LEFT: 0px; WIDTH: 95px; CURSOR: auto; BORDER-BOTTOM: 0px; POSITION: absolute; TOP: 1514px; HEIGHT: 18px" selectedindex="0" pos_rel="false" lineid="lineid" y2="1532" y1="1514" x2="345" x1="250" tag="div">
        <p><strong><font face="arial,helvetica,sans-serif" size="2">Course Name</font></strong></p>
    </div>
    <div id="txtElt11288262309675dIi15v" style="BORDER-RIGHT: 0px; BORDER-TOP: 0px; Z-INDEX: 1565881; LEFT: 40px; BORDER-LEFT: 0px; WIDTH: 430px; CURSOR: auto; BORDER-BOTTOM: 0px; POSITION: absolute; TOP: 1464px; HEIGHT: 34px" selectedindex="0" pos_rel="false" lineid="lineid" y2="1498" y1="1464" x2="470" x1="40" tag="div">
        <p><strong>
        <font face="arial,helvetica,sans-serif" size="2" tag="font">16. Please 
        write below the Course Name in order of preference.</font></strong></p>
        <p tag="p"><strong><font face="Arial" size="2" tag="font">      (Please 
        see the "Instructions to Candidate" for list of courses)</font></strong></p>
    </div>
</div>

One div contains multiple inner divs. My aim is to create a CSS file with styling for these elements. The styles will be extracted from the HTML and placed in the CSS file. The Java code snippet below helps achieve this:

public static Document getStyleInCSSfile(Document aoDoc, String aoPathToWrite, String aoFileName) throws ApplicationException {
    String loValue = null;
    String loID = null;
    String lsContent = "";
    Element loRoot = aoDoc.getRootElement();
    List loTempElementList = loRoot.getChildren();
    int liCounter;
    for (liCounter = 0; liCounter < loTempElementList.size(); liCounter++) {
        Element loTemplateEle = (Element) loTempElementList.get(liCounter);
        String loId=loTemplateEle.getAttribute("id").getValue();
        loID = loTemplateEle.getAttributeValue("id");
        if(null != loID)
        {
            loValue = loTemplateEle.getAttributeValue("style");
            if(loValue!=null && loValue.trim().length()>0)
            {
                loTemplateEle.removeAttribute("style");
                lsContent = lsContent.concat("#"+loID+"{"+loValue+"}\n");
            }
        }
    }
    SaveFormOnLocalUtil.writeToFile(aoPathToWrite,aoFileName,lsContent);
    return aoDoc;
}

Edit : To handle hierarchies efficiently, regex might assist in extracting styling information using SAX parser objects. Any insights on implementing this approach?

Answer №1

Do you think it's efficient to assign a unique style to each individual tag?
If I were in your shoes, I would first check if any other tags share the same style. If all elements with a certain style also have the same 'tag_name', I would simply use the following code:

tag_name{text-transform:uppercase;text-align:center;}

This way, every element with that specific tag name (unless styled differently elsewhere) would inherit this style.
If there are numerous tags with the same style:

.class_name{text-transform:uppercase;text-align:center;}

<tag class="class_name">content</tag>

Answer №2

Consider utilizing SAX over DOM for parsing XML data. With SAX, you can set up a handler that triggers whenever a new tag or attribute is encountered by the parser. For instance, whenever the parser detects the "style" attribute, you can extract its value and save it to a CSS file.

Another option is to leverage Digester from jakarta.apache.org. This tool, which also utilizes SAX, allows for XML configuration (refer to DigesterDigester) that directly maps your value object to the XML document.

Alternatively, you could explore a completely different approach by using unix shell commands like grep and sed. The choice between these solutions should be based on your system requirements and the frequency at which you need to execute the code. For one-time transformations, consider using unix shell scripting. For robust and real-time page updates, a Java-based solution may be more suitable.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for effectively utilizing the :valid pseudo-class in Material-UI components to dynamically alter the border styling

Currently, I am attempting to adjust the border color of Mui TextFields using createTheme from Mui v5 when the input is valid. The border itself is defined within the ::before and ::after pseudoclasses. For the TextFields, I am utilizing variant="stan ...

I'm experiencing an issue with my dropdownlist not triggering the onchange event in AngularJS

I am a beginner in the world of AngularJS and I am trying to extract the values OnChange from a dropdown list. Here is the code that I have experimented with: <div> <select ng-controller="UserSelection as User" ng-model="User.UserSelected" n ...

Learn how to dynamically visualize Python charts on an HTML page with the Flask framework

I have created dynamic charts in Python, but I'm having trouble inserting them into my HTML page. Click here to view my charts and how I expect them to be visualized dynamically. Currently, I can only display the charts as static images on the HTML p ...

The error message "ERR_CONNECTION_TIMED_OUT when trying to access Google APIs fonts

Upon deploying my web project on the client server, I encountered an error and noticed slow page loading. GET https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700,300italic,400italic,600italic net::ERR_CONNECTION_TIMED_OUT The browser ...

Dynamic Data Binding in Ionic 2

One challenge I am facing is with creating my own info window for a Google Maps marker. Whenever I click on the marker, a div is displayed but the information inside the div does not get updated. It seems like the event.title remains unchanged from its old ...

Maintain consistent width of a page across different mobile devices

Currently, the content on my page does not have any viewport settings. It is simply using a 25% left and right margin for the entire content area. The issue arises when accessing the page from a mobile device, as the width adjusts to match the screen size ...

Using jQuery to alter an href link's attribute

I am currently attempting to modify the content of a href using jQuery. After researching various solutions on this platform, I came across one that I am trying to use for implementation: How to change the href for a hyperlink using jQuery My current app ...

Button in Angular gets stuck when a touchscreen is long pressed

In my Angular2 application, I am facing an issue with a button when running on a Windows 10 touchscreen PC in Chrome. Normally, the button works fine and executes the click function. However, if the button is held for 1-2 seconds, it gets stuck and fails t ...

Looping through multi-dimensional JSON objects with jQuery

Hello there, I'm currently facing some challenges in getting the screen below to work properly: Project progress screen I have generated the following JSON data from PHP and MYSQL. My goal is to display the project alongside user images and names whe ...

Is there a way to have my MUI Typography component display a unique image cursor when hovered over?

After some testing, I found that setting the cursor to cursor: pointer works perfectly fine. However, my goal is to use a custom image as a cursor. The image is saved in both my src and public folders, but I seem to be struggling with the syntax when using ...

Adding a class to an img tag with TinyMCE

Currently, I am utilizing the TinyMCE editor as a standalone editor in my content management system (CMS). Within the CMS, there is an automatic setting that adds a curved border to any image tags within the cms div ID. In certain cases, I require the op ...

What is the best way to incorporate white-space:normal within the text of a jQuery Mobile grid button?

Below is the code for my jQuery Mobile Grid buttons: <div class="ui-grid-b my-breakpoint"> <div class="ui-block-a"><button type="button" data-theme="c"> <img src="res/icon/android/business.png" height="45"><br>Business</ ...

What is the best way to incorporate a linear gradient into the background image using bootstrap?

I'm working on a react app and I'd like to apply a linear gradient of 0.7 to the background image using bootstrap. Can anyone help me with this? <Carousel.Item> <img className='banner-bg d-block w-100 bg-dark bg-gradient &apo ...

jQuery - restrict input field based on the value of a different selected field

Could anyone recommend a jQuery plugin that can achieve the following functionality? For example: <label><input type="checkbox" depends_on="foo=5" name="boo" ... /> Check </label> <select name="foo" ... > <option value="5" se ...

My CSS code is not successfully positioning the items to the right, despite my best efforts

I'm currently working on a website project and facing an issue with aligning the text 'Axxon' to the left of the div-header-gradient class, and the a href positioned to the right of the header. However, my code doesn't seem to be workin ...

Rearrange the position of the divs in every other container

Assume that I have the following HTML structure: <div class="article"> <div class="article_img"></div> <div class="article_preview"></div> </div> Both article_img and article_preview elements have a defined width and ...

Is it possible to create a carousel using a JQuery slideshow that connects the first and last list elements?

I am working on creating a carousel effect with three list elements that should slide in and out of the container when the left or right arrows are clicked. I want the list elements to wrap so that when the last element is reached, it goes back to the firs ...

Addressing Layout Problems When I Enlarge the Browser Width

My website is www.adventureswithross.com When the device width is larger than 601px, I have specific requirements: I need the menu and custom header to be seamlessly connected without any spacing in between. To address the issue of space above the custo ...

Placing an SVG icon on top of a CSS border

I'm currently working on positioning an SVG icon over a CSS border, but I'm running into an issue with the layering of the border. The design calls for the border to be in the background, while the icon should be in the foreground. I'm exper ...

H2 Trigger Fails to Activate

As I work on creating an H2 Trigger, my goal is to have it trigger before executing an Insert query. This is necessary because I need to set an ID in an SQL Table that must first be created in another table. The structure of the table where the insert ope ...