Class Element
- java.lang.Object
-
- eu.maveniverse.domtrip.Node
-
- eu.maveniverse.domtrip.ContainerNode
-
- eu.maveniverse.domtrip.Element
-
public class Element extends ContainerNode
Represents an XML element with attributes and children, preserving original formatting including attribute spacing, quote styles, and element structure.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
Attributeobjects that preserve the original quote style, whitespace, and raw values. ThesetAttributemethods 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:
ContainerNode,Attribute,NamespaceContext
-
-
Nested Class Summary
-
Nested classes/interfaces inherited from class eu.maveniverse.domtrip.Node
Node.NodeType
-
-
Field Summary
-
Fields inherited from class eu.maveniverse.domtrip.ContainerNode
children
-
Fields inherited from class eu.maveniverse.domtrip.Node
modified, parent, precedingWhitespace
-
-
Constructor Summary
Constructors Constructor Description Element(java.lang.String name)Create a new Element with the given tag name.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Deprecated Methods Modifier and Type Method Description DomTripVisitor.Actionaccept(DomTripVisitor visitor)Accepts a visitor for depth-first tree traversal.java.lang.Stringattribute(java.lang.String name)Gets the value of the specified attribute.Elementattribute(java.lang.String name, java.lang.String value)Sets an attribute value, preserving existing formatting when the attribute already exists.Elementattribute(java.lang.String name, java.lang.String value, QuoteStyle quoteStyle)Sets an attribute value with a specific quote style.AttributeattributeObject(java.lang.String name)Gets the Attribute object for the specified attribute name.ElementattributeObject(java.lang.String name, Attribute attribute)Sets an attribute using an Attribute object.java.util.Map<java.lang.String,Attribute>attributeObjects()Gets all attribute objects with their formatting information.QuoteStyleattributeQuote(java.lang.String attributeName)Gets the quote style for the specified attribute.ElementattributeQuote(java.lang.String attributeName, QuoteStyle quoteStyle)Sets the quote character for the specified attribute.java.util.Map<java.lang.String,java.lang.String>attributes()Gets all attributes as a map of names to values.java.lang.StringattributeWhitespace(java.lang.String attributeName)Gets the preceding whitespace for the specified attribute.ElementattributeWhitespace(java.lang.String attributeName, java.lang.String whitespace)Sets the preceding whitespace for the specified attribute.static Elementcdata(java.lang.String name, java.lang.String content)Creates a CDATA element.java.util.Optional<Element>childElement(QName qname)Finds the first child element with the given QName.java.util.Optional<Element>childElement(java.lang.String name)Finds the first child element with the given name.java.util.stream.Stream<Element>childElements()Finds all child elements.java.util.stream.Stream<Element>childElements(QName qname)Finds all child elements with the given QName.java.util.stream.Stream<Element>childElements(java.lang.String name)Finds all child elements with the given name.java.lang.StringchildText(java.lang.String childName)Gets the text content of a child element, or returns null if not found.java.lang.StringchildTextOr(java.lang.String childName, java.lang.String defaultValue)Gets the text content of an optional child element with the given name.java.lang.StringchildTextRequired(java.lang.String childName)Gets the text content of a required child element with the given name.java.lang.StringchildTextTrimmed(java.lang.String childName)Gets the trimmed text content of a child element, or returns null if not found.Elementclone()Deprecated.Usecopy()instead.java.lang.StringcloseTagWhitespace()Gets the whitespace within the closing tag (before the element name).ElementcloseTagWhitespace(java.lang.String whitespace)Sets the whitespace within the closing tag (before the element name).static Commentcomment(java.lang.String content)Creates a comment node.Elementcopy()Creates a deep copy of this node.java.util.Optional<Element>descendant(QName qname)Finds the first descendant element with the given QName.java.util.Optional<Element>descendant(java.lang.String name)Finds the first descendant element with the given name.java.util.stream.Stream<Element>descendants()Returns a stream of all descendant elements (depth-first traversal).java.util.stream.Stream<Element>descendants(QName qname)Finds all descendant elements with the given QName.java.util.stream.Stream<Element>descendants(java.lang.String name)Finds all descendant elements with the given name (convenience method).booleanhasAttribute(java.lang.String name)Checks if this element has the specified attribute.booleaninNamespace(java.lang.String namespaceURI)Checks if this element is in the specified namespace.java.lang.StringinnerPrecedingWhitespace()Gets the whitespace immediately before the closing tag.ElementinnerPrecedingWhitespace(java.lang.String whitespace)Sets the whitespace immediately before the closing tag.java.lang.StringlocalName()Gets the local name part of this element (without namespace prefix).java.lang.Stringname()Gets the name (tag name) of this element.Elementname(java.lang.String name)Sets the element name.NamespaceContextnamespaceContext()Gets the namespace context for this element.java.lang.StringnamespaceDeclaration(java.lang.String prefix)Gets a namespace declaration for the given prefix.ElementnamespaceDeclaration(java.lang.String prefix, java.lang.String namespaceURI)Sets a namespace declaration attribute (xmlns or xmlns:prefix).java.lang.StringnamespaceURI()Gets the namespace URI of this element.static Elementof(QName qname)Creates an element from a QName.static Elementof(java.lang.String name)Creates a simple element.java.lang.StringopenTagWhitespace()Gets the whitespace within the opening tag (before the closing >).ElementopenTagWhitespace(java.lang.String whitespace)Sets the whitespace within the opening tag (before the closing >).java.lang.StringoriginalCloseTag()Gets the original closing tag as it appeared in the source XML.ElementoriginalCloseTag(java.lang.String originalCloseTag)Set the materialized original closing tag and disable source-backed close-tag slicing.java.lang.StringoriginalOpenTag()Provide the original open tag exactly as it appeared in the source, or an empty string if none is available.ElementoriginalOpenTag(java.lang.String originalOpenTag)Set the materialized original open tag and disable source-backed tag slicing.Elementparent(ContainerNode parent)Sets the parent container node of this node.java.util.Optional<Element>path(QName... path)Finds an element by following a path of QNames from this element.java.util.Optional<Element>path(java.lang.String... path)Finds an element by following a path of element names from this element.ElementprecedingWhitespace(java.lang.String whitespace)Sets the whitespace that precedes this node.java.lang.Stringprefix()Gets the namespace prefix of this element.static ProcessingInstructionprocessingInstruction(java.lang.String target, java.lang.String data)Creates a processing instruction.java.lang.StringqualifiedName()Gets the qualified name of this element (prefix:localName or just localName).ElementQueryquery()Creates a fluent query builder for finding elements.voidremoveAttribute(java.lang.String name)Removes the specified attribute from this element.voidremoveNamespaceDeclaration(java.lang.String prefix)Removes a namespace declaration.java.util.List<Element>select(java.lang.String expression)Evaluates a mini-XPath expression against this element and returns all matching elements.java.util.Optional<Element>selectFirst(java.lang.String expression)Evaluates a mini-XPath expression against this element and returns the first match.booleanselfClosing()Checks if this element is self-closing.ElementselfClosing(boolean selfClosing)Sets whether this element should be self-closing.static ElementselfClosing(java.lang.String name)Creates a self-closing element.static Elementtext(QName qname, java.lang.String content)Creates an element from a QName with text content.static Elementtext(java.lang.String name, java.lang.String content)Creates a simple text element.java.util.Optional<Text>textChild()Finds the first text child node.java.lang.StringtextContent()Gets the text content of this element (concatenates all text children)ElementtextContent(java.lang.String content)Sets the text content, replacing all existing text children.java.lang.StringtextContentOr(java.lang.String defaultValue)Gets the text content of this element, returning a default value if the text content is null or empty.java.lang.StringtextContentTrimmed()Gets the text content with leading and trailing whitespace removed.java.lang.StringtextContentTrimmedOr(java.lang.String defaultValue)Gets the text content with leading and trailing whitespace removed if non-empty and non-null, otherwise returns the default value.ElementtextPreservingWhitespace(java.lang.String content)Sets the text content while preserving existing whitespace patterns.java.lang.StringtoString()voidtoXml(java.lang.StringBuilder sb)Serialize this element into XML and append the result to the supplied StringBuilder.Node.NodeTypetype()Returns the node type for this element.TreeWalkerwalk()Creates a lambda-friendly tree walker starting from this element.static ElementwithAttributes(java.lang.String name, java.util.Map<java.lang.String,java.lang.String> attributes)Creates an element with attributes.static ElementwithTextAndAttributes(java.lang.String name, java.lang.String content, java.util.Map<java.lang.String,java.lang.String> attributes)Creates an element with text content and attributes.-
Methods inherited from class eu.maveniverse.domtrip.ContainerNode
addChild, child, childCount, children, clearChildren, clearModified, findTextNode, firstChild, getNode, hasChildElements, hasTextContent, insertChild, insertChildAfter, insertChildBefore, isEmpty, lastChild, removeChild, replaceChild
-
Methods inherited from class eu.maveniverse.domtrip.Node
depth, document, isDescendantOf, isModified, markModified, nextSibling, nextSiblingElement, parent, parentElement, precedingWhitespace, previousSibling, previousSiblingElement, siblingIndex, toXml
-
-
-
-
Constructor Detail
-
Element
public Element(java.lang.String name) throws DomTripExceptionCreate 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 Detail
-
type
public Node.NodeType type()
Returns the node type for this element.- Specified by:
typein classNode- Returns:
Node.NodeType.ELEMENT
-
name
public java.lang.String 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:
localName(),prefix()
-
name
public Element name(java.lang.String name)
Sets the element name.- Parameters:
name- the new element name- Returns:
- this element for method chaining
-
attribute
public java.lang.String attribute(java.lang.String name)
Gets the value of the specified attribute.- Parameters:
name- the attribute name- Returns:
- the attribute value, or null if the attribute doesn't exist
-
attribute
public Element attribute(java.lang.String name, java.lang.String value)
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(String, String, QuoteStyle),attributeObject(String)
-
attribute
public Element attribute(java.lang.String name, java.lang.String value, QuoteStyle quoteStyle)
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:
attribute(String, String)
-
removeAttribute
public void removeAttribute(java.lang.String name)
Removes the specified attribute from this element.- Parameters:
name- the name of the attribute to remove
-
attributes
public java.util.Map<java.lang.String,java.lang.String> attributes()
Gets all attributes as a map of names to values.- Returns:
- a map containing all attribute names and their values
-
attributeObjects
public java.util.Map<java.lang.String,Attribute> attributeObjects()
Gets all attribute objects with their formatting information.- Returns:
- a map of attribute names to Attribute objects
-
hasAttribute
public boolean hasAttribute(java.lang.String name)
Checks if this element has the specified attribute.- Parameters:
name- the attribute name to check- Returns:
- true if the attribute exists, false otherwise
-
attributeObject
public Attribute attributeObject(java.lang.String name)
Gets the Attribute object for the specified attribute name.- Parameters:
name- the attribute name- Returns:
- the Attribute object, or null if the attribute doesn't exist
-
attributeObject
public Element attributeObject(java.lang.String name, Attribute attribute)
Sets an attribute using an Attribute object.- Parameters:
name- the attribute nameattribute- the Attribute object to set- Returns:
- this element for method chaining
-
attributeWhitespace
public Element attributeWhitespace(java.lang.String attributeName, java.lang.String whitespace)
Sets the preceding whitespace for the specified attribute.- Parameters:
attributeName- the name of the attributewhitespace- the whitespace to set before the attribute- Returns:
- this element for method chaining
-
attributeWhitespace
public java.lang.String attributeWhitespace(java.lang.String attributeName)
Gets the preceding whitespace for the specified attribute.- Parameters:
attributeName- the name of the attribute- Returns:
- the preceding whitespace, or a single space if not set
-
attributeQuote
public Element attributeQuote(java.lang.String attributeName, QuoteStyle quoteStyle)
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
public QuoteStyle attributeQuote(java.lang.String attributeName)
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
public Element parent(ContainerNode 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.
- Overrides:
parentin classNode- Parameters:
parent- the parent container node to set, or null to clear the parent- Returns:
- this element for method chaining
- See Also:
Node.parent()
-
precedingWhitespace
public Element precedingWhitespace(java.lang.String whitespace)
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:
Node.precedingWhitespace()
-
openTagWhitespace
public java.lang.String openTagWhitespace()
Gets the whitespace within the opening tag (before the closing >).- Returns:
- the whitespace within the opening tag
-
openTagWhitespace
public Element openTagWhitespace(java.lang.String whitespace)
Sets the whitespace within the opening tag (before the closing >).- Parameters:
whitespace- the whitespace to set- Returns:
- this element for method chaining
-
closeTagWhitespace
public java.lang.String closeTagWhitespace()
Gets the whitespace within the closing tag (before the element name).- Returns:
- the whitespace within the closing tag
-
closeTagWhitespace
public Element closeTagWhitespace(java.lang.String whitespace)
Sets the whitespace within the closing tag (before the element name).- Parameters:
whitespace- the whitespace to set- Returns:
- this element for method chaining
-
innerPrecedingWhitespace
public java.lang.String 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:
Node.precedingWhitespace()
-
innerPrecedingWhitespace
public Element innerPrecedingWhitespace(java.lang.String whitespace)
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:
innerPrecedingWhitespace()
-
selfClosing
public boolean selfClosing()
Checks if this element is self-closing.- Returns:
- true if the element is self-closing, false otherwise
-
selfClosing
public Element selfClosing(boolean 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
public java.lang.String 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
public Element originalOpenTag(java.lang.String originalOpenTag)
Set the materialized original open tag and disable source-backed tag slicing.- Parameters:
originalOpenTag- the original opening tag; null is treated as an empty string- Returns:
- this element for method chaining
-
originalCloseTag
public java.lang.String 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
public Element originalCloseTag(java.lang.String 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
public void toXml(java.lang.StringBuilder sb)
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.- Specified by:
toXmlin classNode- Parameters:
sb- the StringBuilder to append the XML representation to- See Also:
Node.toXml()
-
textContent
public java.lang.String 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
public java.lang.String textContentOr(java.lang.String defaultValue)
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
public Element textContent(java.lang.String content)
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(String),textContent()
-
textPreservingWhitespace
public Element textPreservingWhitespace(java.lang.String content)
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:
textContent(String),textContent(),textContentTrimmed()
-
textContentTrimmed
public java.lang.String 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:
textContent(),textPreservingWhitespace(String)
-
textContentTrimmedOr
public java.lang.String textContentTrimmedOr(java.lang.String defaultValue)
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:
textContentOr(String)
-
localName
public java.lang.String localName()
Gets the local name part of this element (without namespace prefix).
-
prefix
public java.lang.String prefix()
Gets the namespace prefix of this element. Returns null if the element has no prefix.
-
qualifiedName
public java.lang.String qualifiedName()
Gets the qualified name of this element (prefix:localName or just localName).
-
namespaceURI
public java.lang.String namespaceURI()
Gets the namespace URI of this element. Returns null if the element is not in any namespace.
-
inNamespace
public boolean inNamespace(java.lang.String namespaceURI)
Checks if this element is in the specified namespace.
-
namespaceContext
public NamespaceContext namespaceContext()
Gets the namespace context for this element. Includes all namespace declarations from this element and its ancestors.
-
namespaceDeclaration
public Element namespaceDeclaration(java.lang.String prefix, java.lang.String namespaceURI)
Sets a namespace declaration attribute (xmlns or xmlns:prefix).- Parameters:
prefix- the namespace prefix, or null/empty for default namespacenamespaceURI- the namespace URI- Returns:
- this element for method chaining
-
namespaceDeclaration
public java.lang.String namespaceDeclaration(java.lang.String prefix)
Gets a namespace declaration for the given prefix. Returns null if no declaration is found on this element.
-
removeNamespaceDeclaration
public void removeNamespaceDeclaration(java.lang.String prefix)
Removes a namespace declaration.
-
descendants
public java.util.stream.Stream<Element> descendants()
Returns a stream of all descendant elements (depth-first traversal).
-
childElement
public java.util.Optional<Element> childElement(QName qname)
Finds the first child element with the given QName.- Parameters:
qname- the QName to match- Returns:
- an Optional containing the first matching child element, or empty if none found
-
childElement
public java.util.Optional<Element> childElement(java.lang.String name)
Finds the first child element with the given name.- Parameters:
name- the element name to match- Returns:
- an Optional containing the first matching child element, or empty if none found
-
childTextOr
public java.lang.String childTextOr(java.lang.String childName, java.lang.String defaultValue)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
public java.lang.String childText(java.lang.String childName)
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:
childElement(String),childTextOr(String, String),childTextTrimmed(String)
-
childTextTrimmed
public java.lang.String childTextTrimmed(java.lang.String childName)
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:
childElement(String),childTextOr(String, String),childText(String),textContentTrimmed()
-
childTextRequired
public java.lang.String childTextRequired(java.lang.String childName)
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
public java.util.stream.Stream<Element> childElements(QName qname)
Finds all child elements with the given QName.- Parameters:
qname- the QName to match- Returns:
- a Stream of matching child elements
-
childElements
public java.util.stream.Stream<Element> childElements(java.lang.String name)
Finds all child elements with the given name.- Parameters:
name- the element name to match- Returns:
- a Stream of matching child elements
-
childElements
public java.util.stream.Stream<Element> childElements()
Finds all child elements.- Returns:
- a Stream of all child elements
-
descendant
public java.util.Optional<Element> descendant(QName qname)
Finds the first descendant element with the given QName.- Parameters:
qname- the QName to match- Returns:
- an Optional containing the first matching descendant element, or empty if none found
-
descendant
public java.util.Optional<Element> descendant(java.lang.String name)
Finds the first descendant element with the given name.- Parameters:
name- the element name to match- Returns:
- an Optional containing the first matching descendant element, or empty if none found
-
descendants
public java.util.stream.Stream<Element> descendants(QName qname)
Finds all descendant elements with the given QName.- Parameters:
qname- the QName to match- Returns:
- a Stream of matching descendant elements
-
descendants
public java.util.stream.Stream<Element> descendants(java.lang.String name)
Finds all descendant elements with the given name (convenience method).- Parameters:
name- the element name to match- Returns:
- a Stream of matching descendant elements
-
textChild
public java.util.Optional<Text> textChild()
Finds the first text child node.- Returns:
- an Optional containing the first text child, or empty if none found
-
query
public ElementQuery query()
Creates a fluent query builder for finding elements.- Returns:
- a new ElementQuery for fluent element searching
-
select
public java.util.List<Element> select(java.lang.String expression)
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:
XPathExpression
-
selectFirst
public java.util.Optional<Element> selectFirst(java.lang.String expression)
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:
XPathExpression
-
accept
public DomTripVisitor.Action accept(DomTripVisitor visitor)
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:
java.lang.IllegalArgumentException- if visitor is null- Since:
- 1.3.0
- See Also:
DomTripVisitor
-
walk
public TreeWalker 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:
TreeWalker
-
path
public java.util.Optional<Element> path(java.lang.String... 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
public java.util.Optional<Element> path(QName... path)
Finds an element by following a path of QNames from this element.- Parameters:
path- the path of QNames to follow- Returns:
- an Optional containing the element at the end of the path, or empty if not found
-
copy
public Element 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 public Element clone()
Deprecated.Usecopy()instead.Creates a deep copy of this element.
-
toString
public java.lang.String toString()
- Overrides:
toStringin classjava.lang.Object
-
of
public static Element of(java.lang.String name) throws DomTripException
Creates a simple element.- Parameters:
name- the element name- Returns:
- a new Element
- Throws:
DomTripException
-
of
public static Element of(QName qname) throws DomTripException
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
public static Element text(java.lang.String name, java.lang.String content) throws DomTripException
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
public static Element selfClosing(java.lang.String name) throws DomTripException
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(java.lang.String name, java.util.Map<java.lang.String,java.lang.String> attributes) throws DomTripException
Creates 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(java.lang.String name, java.lang.String content, java.util.Map<java.lang.String,java.lang.String> attributes) throws DomTripException
Creates 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
public static Element cdata(java.lang.String name, java.lang.String content) throws DomTripException
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
public static Element text(QName qname, java.lang.String content) throws DomTripException
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
public static Comment comment(java.lang.String content)
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:
Comment.of(String)
-
processingInstruction
public static ProcessingInstruction processingInstruction(java.lang.String target, java.lang.String data)
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:
ProcessingInstruction.of(String, String)
-
-