import java.util.HashMap;
import java.util.Map;
public class HtmlHelper {
private static final String DEFAULT_VALUE = ""; // Default value if not found
/**
* Safely retrieves an attribute value from an HTML element's attributes.
* Handles cases where the attribute is missing or the element is null.
*
* @param elementAttributes A map of attribute names to values.
* @param attributeName The name of the attribute to retrieve.
* @return The value of the attribute, or DEFAULT_VALUE if not found.
*/
public static String getAttributeValue(Map<String, String> elementAttributes, String attributeName) {
if (elementAttributes == null || attributeName == null || attributeName.isEmpty()) {
return DEFAULT_VALUE; // Handle null/empty input
}
return elementAttributes.getOrDefault(attributeName, DEFAULT_VALUE);
}
/**
* Safely sets an attribute on an HTML element.
* Handles cases where the element is null or the attribute name is invalid.
*
* @param elementAttributes A map of attribute names to values.
* @param attributeName The name of the attribute to set.
* @param attributeValue The value of the attribute.
*/
public static void setAttribute(Map<String, String> elementAttributes, String attributeName, String attributeValue) {
if (elementAttributes == null || attributeName == null || attributeName.isEmpty()) {
return; // Do nothing if input is invalid
}
elementAttributes.put(attributeName, attributeValue);
}
/**
* Checks if an element contains a specific attribute.
* @param elementAttributes A map of attribute names to values.
* @param attributeName The name of the attribute to check.
* @return True if the attribute exists, false otherwise.
*/
public static boolean hasAttribute(Map<String, String> elementAttributes, String attributeName) {
if (elementAttributes == null || attributeName == null || attributeName.isEmpty()) {
return false;
}
return elementAttributes.containsKey(attributeName);
}
/**
* Converts a string to a safe HTML attribute value, escaping special characters.
*
* @param value The string to convert.
* @return The HTML-safe attribute value.
*/
public static String escapeHtml(String value) {
if (value == null) {
return "";
}
return value.replace("&", "&")
.replace("<", "<")
.replace(">", ">")
.replace("\"", """)
.replace("'", "'");
}
/**
* Create a map of attributes.
* @param attributes A string representation of attributes, where key=value pairs are separated by '&'.
* @return A map containing the attributes.
*/
public static Map<String, String> parseAttributes(String attributes) {
Map<String, String> attributeMap = new HashMap<>();
if (attributes != null && !attributes.isEmpty()) {
String[] attributeArray = attributes.split("&");
for (String attribute : attributeArray) {
String[] parts = attribute.split("=");
if (parts.length == 2) {
attributeMap.put(parts[0], parts[1]);
}
}
}
return attributeMap;
}
}
Add your comment