Class Element
The Element class is the core building block for XML documents, representing XML elements with their attributes, child nodes, and namespace information. It maintains lossless formatting preservation during round-trip parsing and serialization operations.
Capabilities:
- Attribute Management - Preserves attribute order, quote styles, and whitespace
- Namespace Support - XML namespace handling with prefix resolution
- Child Navigation - Methods for finding and manipulating child elements
- Self-Closing Support - Handles self-closing tags
- Formatting Preservation - Maintains original tag formatting and whitespace
Usage Examples:
// Create elements using factory methods
Element root = Element.of("root").attribute("id", "main");
Element textElement = Element.text("child", "Hello World");
Element selfClosing = Element.selfClosing("br");
// Add child elements
root.addNode(textElement);
root.addNode(Element.text("version", "1.0.0"));
// Navigate children
Optional<Element> found = root.child("child");
Stream<Element> children = root.children("item");
// Namespace handling
QName soapEnvelope = QName.of("http://schemas.xmlsoap.org/soap/envelope/", "Envelope", "soap");
Element nsElement = Element.of(soapEnvelope);
// Complex elements with fluent API
Element dependency = Element.of("dependency")
.attribute("scope", "test");
dependency.addNode(Element.text("groupId", "junit"));
dependency.addNode(Element.text("artifactId", "junit"));
Attribute Handling:
Elements maintain attributes using Attribute objects that preserve
the original quote style, whitespace, and raw values. The setAttribute
methods automatically preserve existing formatting when updating attributes:
// Setting new attributes uses default formatting
element.setAttribute("class", "important"); // Uses default double quotes
element.setAttribute("style", "color: red", '\''); // Uses single quotes
// Updating existing attributes preserves original formatting
element.setAttribute("class", "updated"); // Preserves original quotes/whitespace
String value = element.attribute("class"); // Returns "updated"
// For advanced formatting control, use attribute objects directly
element.attributeObject("class").value("manual");
- See Also:
-
Nested Class Summary
Nested classes/interfaces inherited from class Node
Node.NodeType -
Field Summary
Fields inherited from class ContainerNode
childrenFields inherited from class Node
modified, parent, precedingWhitespace -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionaccept(DomTripVisitor visitor) Accepts a visitor for depth-first tree traversal.Gets the value of the specified attribute.Sets an attribute value, preserving existing formatting when the attribute already exists.attribute(String name, String value, QuoteStyle quoteStyle) Sets an attribute value with a specific quote style.attributeObject(String name) Gets the Attribute object for the specified attribute name.attributeObject(String name, Attribute attribute) Sets an attribute using an Attribute object.Gets all attribute objects with their formatting information.attributeQuote(String attributeName) Gets the quote style for the specified attribute.attributeQuote(String attributeName, QuoteStyle quoteStyle) Sets the quote character for the specified attribute.Gets all attributes as a map of names to values.attributeWhitespace(String attributeName) Gets the preceding whitespace for the specified attribute.attributeWhitespace(String attributeName, String whitespace) Sets the preceding whitespace for the specified attribute.static ElementCreates a CDATA element.childElement(QName qname) Finds the first child element with the given QName.childElement(String name) Finds the first child element with the given name.Finds all child elements.childElements(QName qname) Finds all child elements with the given QName.childElements(String name) Finds all child elements with the given name.Gets the text content of a child element, or returns null if not found.childTextOr(String childName, String defaultValue) Gets the text content of an optional child element with the given name.childTextRequired(String childName) Gets the text content of a required child element with the given name.childTextTrimmed(String childName) Gets the trimmed text content of a child element, or returns null if not found.clone()Deprecated.Gets the whitespace within the closing tag (before the element name).closeTagWhitespace(String whitespace) Sets the whitespace within the closing tag (before the element name).static CommentCreates a comment node.copy()Creates a deep copy of this node.descendant(QName qname) Finds the first descendant element with the given QName.descendant(String name) Finds the first descendant element with the given name.Returns a stream of all descendant elements (depth-first traversal).descendants(QName qname) Finds all descendant elements with the given QName.descendants(String name) Finds all descendant elements with the given name (convenience method).booleanhasAttribute(String name) Checks if this element has the specified attribute.booleaninNamespace(String namespaceURI) Checks if this element is in the specified namespace.Gets the whitespace immediately before the closing tag.innerPrecedingWhitespace(String whitespace) Sets the whitespace immediately before the closing tag.Gets the local name part of this element (without namespace prefix).name()Gets the name (tag name) of this element.Sets the element name.Gets the namespace context for this element.namespaceDeclaration(String prefix) Gets a namespace declaration for the given prefix.namespaceDeclaration(String prefix, String namespaceURI) Sets a namespace declaration attribute (xmlns or xmlns:prefix).Gets the namespace URI of this element.static ElementCreates an element from a QName.static ElementCreates a simple element.Gets the whitespace within the opening tag (before the closing >).openTagWhitespace(String whitespace) Sets the whitespace within the opening tag (before the closing >).Gets the original closing tag as it appeared in the source XML.originalCloseTag(String originalCloseTag) Set the materialized original closing tag and disable source-backed close-tag slicing.Provide the original open tag exactly as it appeared in the source, or an empty string if none is available.originalOpenTag(String originalOpenTag) Set the materialized original open tag and disable source-backed tag slicing.parent(ContainerNode parent) Sets the parent container node of this node.Finds an element by following a path of QNames from this element.Finds an element by following a path of element names from this element.precedingWhitespace(String whitespace) Sets the whitespace that precedes this node.prefix()Gets the namespace prefix of this element.static ProcessingInstructionprocessingInstruction(String target, String data) Creates a processing instruction.Gets the qualified name of this element (prefix:localName or just localName).query()Creates a fluent query builder for finding elements.voidremoveAttribute(String name) Removes the specified attribute from this element.voidremoveNamespaceDeclaration(String prefix) Removes a namespace declaration.Evaluates a mini-XPath expression against this element and returns all matching elements.selectFirst(String expression) Evaluates a mini-XPath expression against this element and returns the first match.booleanChecks if this element is self-closing.selfClosing(boolean selfClosing) Sets whether this element should be self-closing.static ElementselfClosing(String name) Creates a self-closing element.static ElementCreates an element from a QName with text content.static ElementCreates a simple text element.Finds the first text child node.Gets the text content of this element (concatenates all text children)textContent(String content) Sets the text content, replacing all existing text children.textContentOr(String defaultValue) Gets the text content of this element, returning a default value if the text content is null or empty.Gets the text content with leading and trailing whitespace removed.textContentTrimmedOr(String defaultValue) Gets the text content with leading and trailing whitespace removed if non-empty and non-null, otherwise returns the default value.textPreservingWhitespace(String content) Sets the text content while preserving existing whitespace patterns.toString()voidtoXml(StringBuilder sb) Serialize this element into XML and append the result to the supplied StringBuilder.type()Returns the node type for this element.walk()Creates a lambda-friendly tree walker starting from this element.static ElementwithAttributes(String name, Map<String, String> attributes) Creates an element with attributes.static ElementCreates an element with text content and attributes.Methods inherited from class ContainerNode
addChild, child, childCount, children, clearChildren, clearModified, findTextNode, firstChild, getNode, hasChildElements, hasTextContent, insertChild, insertChildAfter, insertChildBefore, isEmpty, lastChild, removeChild, replaceChildMethods inherited from class Node
depth, document, isDescendantOf, isModified, markModified, nextSibling, nextSiblingElement, parent, parentElement, precedingWhitespace, previousSibling, previousSiblingElement, siblingIndex, toXml
-
Constructor Details
-
Element
Create a new Element with the given tag name.The element is initialized with an empty, order-preserving attribute map, default (empty) whitespace/formatting fields, and is not self-closing.
- Parameters:
name- the element's tag name; leading/trailing whitespace is trimmed- Throws:
DomTripException- ifnameis null or blank
-
-
Method Details
-
type
Returns the node type for this element.- Specified by:
typein classNode- Returns:
Node.NodeType.ELEMENT
-
name
Gets the name (tag name) of this element.For namespaced elements, this returns the full qualified name including the prefix (e.g., "soap:Envelope"). Use
localName()to get just the local part.- Returns:
- the element name
- See Also:
-
name
-
attribute
-
attribute
Sets an attribute value, preserving existing formatting when the attribute already exists.When setting an attribute that already exists, this method preserves the original quote style, whitespace, and other formatting properties. For new attributes, it uses default formatting (double quotes, single space preceding whitespace).
Examples:
// Original: <element attr1='existing' /> element.attribute("attr1", "updated"); // Result: <element attr1='updated' /> (preserves single quotes) element.attribute("attr2", "new"); // Result: <element attr1='updated' attr2="new" /> (uses default double quotes)- Parameters:
name- the attribute namevalue- the attribute value- Returns:
- this element for method chaining
- See Also:
-
attribute
Sets an attribute value with a specific quote style.When setting an attribute that already exists, this method preserves the original preceding whitespace but uses the specified quote style. For new attributes, it uses the specified quote style with default whitespace (single space).
- Parameters:
name- the attribute namevalue- the attribute valuequoteStyle- the quote style to use (SINGLE or DOUBLE)- Returns:
- this element for method chaining
- See Also:
-
removeAttribute
Removes the specified attribute from this element.- Parameters:
name- the name of the attribute to remove
-
attributes
-
attributeObjects
-
hasAttribute
Checks if this element has the specified attribute.- Parameters:
name- the attribute name to check- Returns:
- true if the attribute exists, false otherwise
-
attributeObject
-
attributeObject
-
attributeWhitespace
-
attributeWhitespace
-
attributeQuote
Sets the quote character for the specified attribute.- Parameters:
attributeName- the name of the attributequoteStyle- the quote style to use (SINGLE or DOUBLE)- Returns:
- this element for method chaining
-
attributeQuote
Gets the quote style for the specified attribute.- Parameters:
attributeName- the name of the attribute- Returns:
- the quote style, or DOUBLE if not set
-
parent
Sets the parent container node of this node.This method is typically called automatically when adding nodes to containers. Manual use should be done carefully to maintain tree consistency.
-
precedingWhitespace
Sets the whitespace that precedes this node.This method allows control over the whitespace formatting before this node when serializing to XML.
- Overrides:
precedingWhitespacein classNode- Parameters:
whitespace- the whitespace string to set, null is treated as empty string- Returns:
- this element for method chaining
- See Also:
-
openTagWhitespace
Gets the whitespace within the opening tag (before the closing >).- Returns:
- the whitespace within the opening tag
-
openTagWhitespace
-
closeTagWhitespace
Gets the whitespace within the closing tag (before the element name).- Returns:
- the whitespace within the closing tag
-
closeTagWhitespace
-
innerPrecedingWhitespace
Gets the whitespace immediately before the closing tag.This field is used for elements that contain only whitespace content (no child elements). It represents the whitespace that appears just before the closing tag, typically used for proper indentation.
Example:
// XML: <parent>\n \n</parent> String whitespace = element.innerPrecedingWhitespace(); // "\n"- Returns:
- the inner preceding whitespace, or empty string if none
- See Also:
-
innerPrecedingWhitespace
Sets the whitespace immediately before the closing tag.Use this method to control the whitespace that appears immediately before the closing tag in elements that contain only whitespace content. This is typically used for proper indentation of the closing tag.
Example:
element.innerPrecedingWhitespace("\n"); // Results in: <element>content\n</element> (whitespace before closing tag)- Parameters:
whitespace- the whitespace to set (null is treated as empty string)- Returns:
- this element for method chaining
- See Also:
-
selfClosing
public boolean selfClosing()Checks if this element is self-closing.- Returns:
- true if the element is self-closing, false otherwise
-
selfClosing
Sets whether this element should be self-closing.- Parameters:
selfClosing- true to make the element self-closing, false otherwise- Returns:
- this element for method chaining
-
originalOpenTag
Provide the original open tag exactly as it appeared in the source, or an empty string if none is available. If the element was parsed from a source buffer and the original open-tag slice is available, the tag is materialized from that source on first access.- Returns:
- the original opening tag string, or empty string if not available
-
originalOpenTag
-
originalCloseTag
Gets the original closing tag as it appeared in the source XML.- Returns:
- the original closing tag string, or empty string if not available
-
originalCloseTag
Set the materialized original closing tag and disable source-backed close-tag slicing. If `originalCloseTag` is null, an empty string is stored. Calling this method clears any source-backed close-tag indices so future preserved serialization will use the provided string.- Parameters:
originalCloseTag- the original closing tag string (null is stored as an empty string)- Returns:
- this element for method chaining
-
toXml
Serialize this element into XML and append the result to the supplied StringBuilder. If the element has not been modified and an original open tag is available, the original tag formatting is preserved; otherwise the element is serialized from scratch using the element's current state. -
textContent
Gets the text content of this element (concatenates all text children)- Overrides:
textContentin classContainerNode- Returns:
- the text content of this node (concatenates all text children).
-
textContentOr
Gets the text content of this element, returning a default value if the text content is null or empty.This is a convenience method for getting text content with a fallback value.
Example:
Element scope = dependency.child("scope").orElse(null); String scopeValue = scope != null ? scope.textContentOr("compile") : "compile"; // Or more simply: String scopeValue = dependency.child("scope") .map(e -> e.textContentOr("compile")) .orElse("compile");- Parameters:
defaultValue- the default value to return if text content is null or empty- Returns:
- the text content or default value
- Since:
- 0.3.0
-
textContent
Sets the text content, replacing all existing text children.Note: This method replaces all text children and does not preserve existing whitespace patterns. For whitespace-preserving updates, use
textPreservingWhitespace(String)instead.- Parameters:
content- the new text content- Returns:
- this element for method chaining
- See Also:
-
textPreservingWhitespace
Sets the text content while preserving existing whitespace patterns.This method attempts to preserve the whitespace structure of the existing text content when updating to new content. If the element has existing text with leading/trailing whitespace, the same pattern will be applied to the new content.
Examples:
// Original: <item> old value </item> element.textPreservingWhitespace("new value"); // Result: <item> new value </item> // Original: <item>old value</item> element.textPreservingWhitespace("new value"); // Result: <item>new value</item>- Parameters:
content- the new text content- Returns:
- this element for method chaining
- See Also:
-
textContentTrimmed
Gets the text content with leading and trailing whitespace removed.This is a convenience method that returns the trimmed text content without modifying the original content. Useful for getting clean content for processing while preserving the original formatting.
- Returns:
- the text content with leading and trailing whitespace removed
- See Also:
-
textContentTrimmedOr
Gets the text content with leading and trailing whitespace removed if non-empty and non-null, otherwise returns the default value.This is a convenience method that returns the trimmed text content without modifying the original content. Useful for getting clean content for processing while preserving the original formatting.
- Returns:
- the text content with leading and trailing whitespace removed or default value
- Since:
- 0.3.1
- See Also:
-
localName
Gets the local name part of this element (without namespace prefix). -
prefix
Gets the namespace prefix of this element. Returns null if the element has no prefix. -
qualifiedName
Gets the qualified name of this element (prefix:localName or just localName). -
namespaceURI
Gets the namespace URI of this element. Returns null if the element is not in any namespace. -
inNamespace
Checks if this element is in the specified namespace. -
namespaceContext
Gets the namespace context for this element. Includes all namespace declarations from this element and its ancestors. -
namespaceDeclaration
-
namespaceDeclaration
-
removeNamespaceDeclaration
Removes a namespace declaration. -
descendants
-
childElement
-
childElement
-
childTextOr
Gets the text content of an optional child element with the given name.This is a convenience method that combines child element lookup and text content extraction with a default value, making it useful for reading optional configuration values. If the child element exists but has no text content (empty element), the default value is returned.
Example:
Element dependency = ...; // Get scope with default value "compile" String scope = dependency.childTextOr("scope", "compile"); // Get optional classifier (returns null if not present) String classifier = dependency.childTextOr("classifier", null);- Parameters:
childName- the name of the child elementdefaultValue- the default value to return if child is not found or has no text content- Returns:
- the text content of the child or default value
- Since:
- 0.3.0
-
childText
Gets the text content of a child element, or returns null if not found.This is a convenience method that provides a simple way to get child element text content with null fallback instead of handling Optional.
- Parameters:
childName- the child element name- Returns:
- the text content of the child element, or null if not found
- See Also:
-
childTextTrimmed
Gets the trimmed text content of a child element, or returns null if not found.This is a convenience method that provides a simple way to get trimmed child element text content with null fallback instead of handling Optional.
- Parameters:
childName- the child element name- Returns:
- the trimmed text content of the child element, or null if not found
- See Also:
-
childTextRequired
Gets the text content of a required child element with the given name.This method is useful when a child element is mandatory and you want to fail fast with a clear error message if it's missing.
Example:
Element dependency = ...; // Get required groupId (throws if missing) String groupId = dependency.childTextRequired("groupId");- Parameters:
childName- the name of the child element- Returns:
- the text content of the child
- Throws:
DomTripException- if the child element is not found- Since:
- 0.3.0
-
childElements
-
childElements
-
childElements
-
descendant
-
descendant
-
descendants
-
descendants
-
textChild
-
query
Creates a fluent query builder for finding elements.- Returns:
- a new ElementQuery for fluent element searching
-
select
Evaluates a mini-XPath expression against this element and returns all matching elements.This is a convenience method that compiles and evaluates the expression in one step. For repeated evaluation of the same expression, use
XPathExpression.compile(String)to compile once and reuse.Examples:
List<Element> deps = root.select("dependencies/dependency"); List<Element> allDeps = root.select("//dependency"); List<Element> testDeps = root.select("//dependency[@scope='test']");- Parameters:
expression- the mini-XPath expression- Returns:
- a list of matching elements, never null
- Throws:
DomTripException- if the expression is invalid- Since:
- 1.3.0
- See Also:
-
selectFirst
Evaluates a mini-XPath expression against this element and returns the first match.This is a convenience method that compiles and evaluates the expression in one step. For repeated evaluation of the same expression, use
XPathExpression.compile(String)to compile once and reuse.Examples:
Optional<Element> dep = root.selectFirst("//dependency[groupId='junit']"); Optional<Element> ver = root.selectFirst("project/version");- Parameters:
expression- the mini-XPath expression- Returns:
- an Optional containing the first matching element, or empty if none found
- Throws:
DomTripException- if the expression is invalid- Since:
- 1.3.0
- See Also:
-
accept
Accepts a visitor for depth-first tree traversal.Calls
DomTripVisitor.enterElement(Element)before visiting children andDomTripVisitor.exitElement(Element)after. IfenterElementreturnsDomTripVisitor.Action.SKIP, children are not visited butexitElementis still called. If any visit method returnsDomTripVisitor.Action.STOP, traversal aborts immediately.- Specified by:
acceptin classNode- Parameters:
visitor- the visitor to accept- Returns:
- the action indicating how traversal should proceed
- Throws:
IllegalArgumentException- if visitor is null- Since:
- 1.3.0
- See Also:
-
walk
Creates a lambda-friendly tree walker starting from this element.This provides a fluent API alternative to implementing
DomTripVisitordirectly:element.walk() .onEnter(e -> { if ("secret".equals(e.localName())) { e.textContent("***"); return Action.SKIP; } return Action.CONTINUE; }) .onExit(e -> { /* cleanup */ }) .onText(t -> { /* process text */ }) .execute();- Returns:
- a new TreeWalker for fluent traversal configuration
- Since:
- 1.3.0
- See Also:
-
path
Finds an element by following a path of element names from this element.Example:
element.path("dependencies", "dependency")will find the first dependency element under this element's dependencies child.- Parameters:
path- the path of element names to follow- Returns:
- an Optional containing the element at the end of the path, or empty if not found
-
path
-
copy
Creates a deep copy of this node.The copied node will have:
- All properties copied from the original
- All child nodes recursively copied (for container nodes)
- Whitespace and formatting properties preserved
- No parent (parent is set to null)
The copied node and its descendants will have their parent-child relationships properly established within the copied subtree.
-
clone
Deprecated.Usecopy()instead.Creates a deep copy of this element. -
toString
-
of
Creates a simple element.- Parameters:
name- the element name- Returns:
- a new Element
- Throws:
DomTripException
-
of
Creates an element from a QName.- Parameters:
qname- the QName for the element- Returns:
- a new Element with namespace configuration
- Throws:
DomTripException- if qname is null
-
text
Creates a simple text element.Creates an element with the specified name and text content. This is a convenience method for creating elements that contain only text.
- Parameters:
name- the element namecontent- the text content to add- Returns:
- a new Element with text content
- Throws:
DomTripException
-
selfClosing
Creates a self-closing element.Creates an element that will be serialized as a self-closing tag (e.g.,
<br/>instead of<br></br>).- Parameters:
name- the element name- Returns:
- a new self-closing Element
- Throws:
DomTripException
-
withAttributes
public static Element withAttributes(String name, Map<String, String> attributes) throws DomTripExceptionCreates an element with attributes.Creates an element with the specified name and adds all the provided attributes.
- Parameters:
name- the element nameattributes- a map of attribute names to values- Returns:
- a new Element with attributes
- Throws:
DomTripException
-
withTextAndAttributes
public static Element withTextAndAttributes(String name, String content, Map<String, String> attributes) throws DomTripExceptionCreates an element with text content and attributes.Creates an element with the specified name, adds all the provided attributes, and includes the specified text content.
- Parameters:
name- the element namecontent- the text content to addattributes- a map of attribute names to values- Returns:
- a new Element with text content and attributes
- Throws:
DomTripException
-
cdata
Creates a CDATA element.Creates an element with the specified name and adds a CDATA section containing the provided content. CDATA sections preserve content exactly without XML entity escaping.
- Parameters:
name- the element namecontent- the CDATA content to add- Returns:
- a new Element with CDATA content
- Throws:
DomTripException
-
text
Creates an element from a QName with text content.- Parameters:
qname- the QName for the elementcontent- the text content to add- Returns:
- a new Element with namespace configuration and text content
- Throws:
DomTripException- if qname is null
-
comment
Creates a comment node.Creates a Comment node with the specified content. This is a convenience method equivalent to
Comment.of(String).- Parameters:
content- the comment content- Returns:
- a new Comment node
- See Also:
-
processingInstruction
Creates a processing instruction.Creates a ProcessingInstruction node with the specified target and data. This is a convenience method equivalent to
ProcessingInstruction.of(String, String).- Parameters:
target- the processing instruction targetdata- the processing instruction data- Returns:
- a new ProcessingInstruction node
- See Also:
-
copy()instead.