jsoup extract custom data attributes of HTML5 Element in Java

Tags: Java jsoup HTML Parser

In this post, we learn how to use jsoup Java library to extract HTML5 custom data attributes.

Add jsoup library to your Java project

To use jsoup Java library in the Gradle build project, add the following dependency into the build.gradle file.

compile 'org.jsoup:jsoup:1.13.1'

To use jsoup Java library in the Maven build project, add the following dependency into the pom.xml file.

<dependency>
    <groupId>org.jsoup</groupId>
    <artifactId>jsoup</artifactId>
    <version>1.13.1</version>
</dependency>

To download the jsoup-1.13.1.jar file you can visit jsoup download page at jsoup.org/download

Sample HTML File

For example, we have a sample.html file as below.

<!DOCTYPE html>
<html>
<body>
    <div id="container" data-name1="test1" data-name2="test2" data-name3="test3">
    </div>
</body>
</html>

Extract HTML5 Custom Data Attributes

The jsoup library provides Element.dataset() to return HTML5 custom data attributes.

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import java.io.File;
import java.io.IOException;
import java.util.Map;

public class DatasetExample {
    public static void main(String... args) {
        try {
            String fileName = "sample.html";
            File file = new File(fileName);
            Document document = Jsoup.parse(file, "UTF-8");
            Element element = document.getElementById("container");

            Map<String, String> dataset = element.dataset();

            for(Map.Entry<String, String> entry : dataset.entrySet()) {
                System.out.println("Key: " + entry.getKey());
                System.out.println("Value: " + entry.getValue());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Output:
Key: name1
Value: test1
Key: name2
Value: test2
Key: name3
Value: test3

Happy Coding 😊

jsoup extract CSS class name of HTML element in Java

jsoup extract ID and name of HTML element in Java

jsoup extract text and attributes of HTML element in Java

jsoup extract Inner and Outer HTML of HTML Element in Java

jsoup extract JavaScript from HTML script element in Java

jsoup extract Website Title in Java

jsoup parse HTML Document from a Java String

jsoup parse HTML Document from an URL in Java

jsoup parse HTML Document from a File and InputStream in Java

Pretty Printing HTML String in Java using jsoup

Extract All Links of a web page in Java using jsoup

jsoup Get HTML elements by CSS class name in Java

Clean HTML String to get Safe HTML from Untrusted HTML in Java using jsoup

jsoup Get All HTML Elements in Java