Class Xml
XML DOM wrapper facilitating node querying and automatically creating,
validating, and populating classes from/to XML, with support
for XmlConfigurable and JAXB.
XML syntax and white spaces
Some white spaces in element text may be removed when parsed.
To keep them, add the XML standard attribute
xml:space="preserve" to your element. For instance, the
following ensures the four spaces are kept when parsed:
<example xml:space="preserve"> </example>
Empty tags are interpreted as having an empty strings while
self-closing tags have their value interpreted as null.
Non-existing tags have no effect (when loading over an object, that
object current value should remain unchanged).
Checked exceptions are wrapped into an XmlException.
- Since:
- 2.0.0
-
Nested Class Summary
Nested Classes -
Constructor Summary
ConstructorsConstructorDescriptionParse an XML file into an XML document, without consideration for namespaces.Parse an XML stream into an XML document, without consideration for namespaces.Parse an XML string into an XML document, without consideration for namespaces.Creates a new XML with the supplied root element (i.e., tag name), and populate it with the supplied object.Parse an XML file into an XML document, without consideration for namespaces.Creates an XML with the given DOM node. -
Method Summary
Modifier and TypeMethodDescriptionaddDelimitedElementList(String name, String delim, List<?> values) Adds a list of values as a new element after joining them with the given delimiter.addDelimitedElementList(String name, List<?> values) Adds a list of values as a new element after joining them with a comma (CSV).addElement(String tagName) Adds an empty child element to this XML root element.addElement(String tagName, Object value) Adds a child element to this XML root element.addElementList(@NonNull String parentTagName, String tagName, List<?> values) Adds a list of values under a new parent tag name to the current XML and return the added list.addElementList(String tagName, List<?> values) Adds a list of values to the current XML and return the added list.addElementMap(String parentTagName, String tagName, String attributeName, Map<?, ?> map) Adds aMapas a series of elements with a parent element wrapping that group.addElementMap(String tagName, String attributeName, Map<?, ?> map) Adds aMapas a series of elements without a parent element wrapping that group.static voidassertWriteRead(Object object, String elementName) Convenience class for testing that an object annotated with JAXBXmlRootElementor implementingXmlConfigurable(or both) can be written, and read back into an new instance that is equal as perequals(Object).voidcheckDeprecated(String deprecatedXPath, boolean throwException) Checks whether a deprecated configuration entry (without replacement) was specified and log a warning or throw anXmlException.voidcheckDeprecated(String deprecatedXPath, String replacement, boolean throwException) Checks whether a deprecated configuration entry was specified and log a warning or throw anXmlException.clear()Clears this XML by removing all its attributes and elements (i.e., making it an empty tag).computeElementIfAbsent(String tagName, Function<String, Object> function) Computes and adds the element returned by the provided function if an element with the same name is not already present, else, return the existing one.booleanbooleanvoidIf the given expression matches one or more elements, consume those element one by one.<T> TGets the matching element/attribute, converted from string to the given type.<T> TGets the matching element/attribute, converted from string to the given type.getBoolean(String xpathExpression) getBoolean(String xpathExpression, Boolean defaultValue) getCharset(String xpathExpression) getCharset(String xpathExpression, Charset defaultValue) Class<?> <T> Class<T> getClassList(String xpathExpression) Gets values as a list of files.getClassList(String xpathExpression, List<Class<? extends T>> defaultValue) Gets values as a list of files.getDataSize(String xpathExpression) Gets the size of a data expression, in bytes (e.g., 2KB, 1GiB, 3 megabytes, etc).getDataSize(String xpathExpression, DataUnit targetUnit, Long defaultValue) Gets the size of a data expression, in the specified target unit (e.g., 2KB, 1GiB, 3 megabytes, etc).getDataSize(String xpathExpression, Long defaultValue) Gets the size of a data expression, in bytes (e.g., 2KB, 1GiB, 3 megabytes, etc).getDelimitedEnumList(String xpathExpression, Class<E> enumClass, String delimRegex, List<E> defaultValues) Gets a list of enum constants after splitting the matching node value(s) with the given delimiter regular expression.getDelimitedEnumList(String xpathExpression, Class<E> enumClass, List<E> defaultValues) Gets a list of enum constants after splitting the matching node value(s) on commas (CSV).<T> List<T> getDelimitedList(String xpathExpression, Class<T> type) Gets a list of the given type after splitting the matching node value(s) on commas (CSV).<T> List<T> getDelimitedList(String xpathExpression, Class<T> type, String delimRegex) Gets a list of given type after splitting the matching node value(s) with the given delimiter regular expression.<T> List<T> getDelimitedList(String xpathExpression, Class<T> type, String delimRegex, List<? extends T> defaultValues) Gets a list of given type after splitting the matching node value(s) with the given delimiter regular expression.<T> List<T> getDelimitedList(String xpathExpression, Class<T> type, List<T> defaultValues) Gets a list of given type after splitting the matching node value(s) on commas (CSV).getDelimitedStringList(String xpathExpression) Gets a list of strings after splitting the matching node value(s) on commas (CSV).getDelimitedStringList(String xpathExpression, String delimRegex) Gets a list of strings after splitting the matching node value(s) with the given delimiter regular expression.getDelimitedStringList(String xpathExpression, String delimRegex, List<String> defaultValues) Gets a list of strings after splitting the matching node value(s) with the given delimiter regular expression.getDelimitedStringList(String xpathExpression, List<String> defaultValues) Gets a list of strings after splitting the matching node value(s) on commas (CSV).getDimension(String xpathExpression) getDimension(String xpathExpression, Dimension defaultValue) getDuration(String xpathExpression) Gets a duration which can exists as a numerical value or a textual representation of a duration as perDurationParser.getDuration(String xpathExpression, Duration defaultValue) Gets a duration which can exists as a numerical value or a textual representation of a duration as perDurationParser.getDurationMillis(String xpathExpression) Gets a duration in milliseconds which can exists as a numerical value or a textual representation of a duration as perDurationParser.getDurationMillis(String xpathExpression, Long defaultValue) Gets a duration in milliseconds which can exists as a numerical value or a textual representation of a duration as perDurationParser.final <E extends Enum<E>>
EGets an Enum constant matching one of the constants in the provided Enum class, ignoring case.final <E extends Enum<E>>
EGets an Enum constant matching one of the constants in the provided Enum class, ignoring case.getEnumList(String xpathExpression, Class<E> enumClass, List<E> defaultValues) Gets a list of enum constants.final FileGets a file, assuming the node value is a file system path.final FileGets a file, assuming the node value is a file system path.getFileList(String xpathExpression) Gets values as a list of files.getFileList(String xpathExpression, List<File> defaultValue) Gets values as a list of files.getInteger(String xpathExpression) getInteger(String xpathExpression, Integer defaultValue) <T> List<? extends T> Gets the matching list of elements/attributes, converted from string to the given type.<T> List<? extends T> Gets the matching list of elements/attributes, converted from string to the given type.getName()getNode()<T> TCreates a new instance of the class represented by the "class" attribute on the node matching the expression.<T> TCreates a new instance of the class represented by the "class" attribute on the node matching the expression.<T> TgetObjectImpl(Class<?> type, String xpathExpression) Creates a new instance of the class represented by the "class" attribute on the node matching the expression.<T> TgetObjectImpl(Class<?> type, String xpathExpression, T defaultObject) Creates a new instance of the class represented by the "class" attribute on the node matching the expression.<T> List<T> getObjectList(String xpathExpression) Creates an instance list from classes represented by the "class" attribute on the nodes matching the expression.<T> List<T> getObjectList(String xpathExpression, List<T> defaultObjects) Creates an instance list from classes represented by the "class" attribute on the nodes matching the expression.<T> List<T> getObjectListImpl(Class<?> type, String xpathExpression) Creates an instance list from classes represented by the "class" attribute on the nodes matching the expression.<T> List<T> getObjectListImpl(Class<?> type, String xpathExpression, List<T> defaultObjects) Creates an instance list from classes represented by the "class" attribute on the nodes matching the expression.final PathGets a path, assuming the node value is a file system path.final PathGets a path, assuming the node value is a file system path.getPathList(String xpathExpression) Gets values as a list of paths.getPathList(String xpathExpression, List<Path> defaultValue) Gets values as a list of paths.getPattern(String xpathExpression) Gets a regular expression pattern.getPattern(String xpathExpression, Pattern defaultValue) Gets a regular expression pattern.getStringList(String xpathExpression) Gets the matching list of elements/attributes as strings.getStringList(String xpathExpression, List<String> defaultValues) Gets the matching list of elements/attributes as strings.getStringMap(String xpathList, String xpathKey, String xpathValue) Gets the matching map of elements/attributes as strings.getStringMap(String xpathList, String xpathKey, String xpathValue, Map<String, String> defaultValues) Gets the matching map of elements/attributes as strings.Gets this XML direct text content, if any, joining multiple text nodes by a space separator.final URLfinal URLgetURLList(String xpathExpression) getURLList(String xpathExpression, List<URL> defaultValue) Gets the xml subset matching the xpath expression.getXMLList(String xpathExpression) Gets the XML subsets matching the xpath expression.Deprecated.booleanGets whether this XML element has any attributes.booleanGets whether this XML element has any child elements.inthashCode()booleanGets whether this XML has any text content.voidIf the given expression matches an element, consume that element.insertAfter(Xml newXML) Inserts a new XML node after this one, as a sibling of a shared parent.insertBefore(Xml newXML) Inserts a new XML node before this one, as a sibling of a shared parent.booleanbooleanisElementPresent(String xpathExpression) Gets whether the given expression matches an existing element.booleanisEmpty()Gets whether this XML is empty.booleanstatic booleanstatic booleanisXMLConfigurable(Object obj) iterator()Deprecated.Will be removed or visibility reduced in a future release.static XPathnewXPath()Deprecated.UseXpathUtil.newXPath()insteadstatic XPathExpressionnewXPathExpression(String expression) Deprecated.UseXpathUtil.newXPathExpression(String)insteadstatic Xml.Builderstatic Xml.Builderof(InputStream is) static Xml.Builderstatic Xml.Builderstatic Xml.Builderstatic Xml.Builderstatic Xml.Builder<T> T<T> T<T> List<T> parseXMLList(String xpathExpression, @NonNull Function<Xml, T> parser) <T> List<T> parseXMLList(String xpathExpression, @NonNull Function<Xml, T> parser, List<T> defaultValue) <K,V> Map <K, V> parseXMLMap(String xpathExpression, Function<Xml, Map.Entry<K, V>> parser) <K,V> Map <K, V> voidPopulates supplied object with this XML.voidPopulates supplied object with the XML matching the given expression.remove()Removes itself from its XML parent (if any).removeAttribute(String name) Removes an attribute on this XML element.removeElement(String tagName) Removes an element from this XML.Removes this XML direct text content, without impact on attributes and child elements and their content.Rename this XML (element tag name).Replaces the current XML with the provided one.setAttribute(String name, Object value) Sets an attribute on this XML element, converting the supplied object to a string (enums are also converted to lowercase).setAttributes(Map<String, ?> attribs) Sets attributes on this XML element.setDelimitedAttributeList(String name, String delim, List<?> values) Sets a list of values as an attribute after joining them with the given delimiter.setDelimitedAttributeList(String name, List<?> values) Sets a list of values as an attribute after joining them with a comma (CSV).setTextContent(Object textContent) Sets the direct text content of an XML element.stream()toNode()<T> TtoObject()Creates a new instance of the class represented by the "class" attribute on this XML root node.<T> TtoObject(T defaultObject) Creates a new instance of the class represented by the "class" attribute on the given node.<T> TtoObjectImpl(Class<?> type) Creates a new instance of the class represented by the "class" attribute on this XML root node.<T> TtoObjectImpl(Class<?> type, T defaultObject) Creates a new instance of the class represented by the "class" attribute on the given node.toReader()toString()Gets a string representation of this XML.toString(int indent) Gets a string representation of this XML.unwrap()Unwraps this XML by removing the root tag and keeping its child element (and its nested element).voidvalidate()Validates this XML against an XSD schema attached to the class represented in this XML root tag "class" attribute.voidValidates this XML against an XSD schema attached to the class represented in this XML root tag "class" attribute.voidValidates this XML against an XSD schema attached to the class represented in this XML root tag "class" attribute.Wraps this XML by adding a parent element around it.voidvoidvoidvoidMethods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, waitMethods inherited from interface java.lang.Iterable
forEach, spliterator
-
Constructor Details
-
Xml
Parse an XML file into an XML document, without consideration for namespaces.
- Parameters:
file- the XML file to parse- See Also:
-
Xml
Parse an XML file into an XML document, without consideration for namespaces.
- Parameters:
file- the XML file to parse- See Also:
-
Xml
Parse an XML stream into an XML document, without consideration for namespaces.
- Parameters:
reader- the XML stream to parse- See Also:
-
Xml
Parse an XML string into an XML document, without consideration for namespaces.
The supplied "xml" string can either be a well-formed XML or a string without angle brackets. When the later is supplied, it is interpreted as the XML root element name (for a fresh XML).
- Parameters:
xml- the XML string to parse- See Also:
-
Xml
Creates a new XML with the supplied root element (i.e., tag name), and populate it with the supplied object.- Parameters:
rootElement- XML root element nameobj- the object to populate this XML with.- See Also:
-
Xml
Creates an XML with the given DOM node.
- Parameters:
node- the node representing the XML
-
-
Method Details
-
of
-
of
-
of
-
of
-
of
-
of
-
of
-
populate
Populates supplied object with the XML matching the given expression. If there is no match, the object does not get populated. Takes into consideration whether the target object implements
XmlConfigurableor JAXB.Performs XML validation if the target object has an associated schema.
- Parameters:
targetObject- object to populate with this XMLxpathExpression- XPath expression
-
populate
Populates supplied object with this XML. Takes into consideration whether the target object implements
XmlConfigurableor JAXB.Performs XML validation if the target object has an associated schema.
Invoking this method with a
nulltarget has no effect (returns an empty list).- Parameters:
targetObject- object to populate with this XML
-
toObject
public <T> T toObject()Creates a new instance of the class represented by the "class" attribute on this XML root node. The class must have an empty constructor. If the class is an instance of
XmlConfigurable, the object created will be automatically populated by invoking theXmlConfigurable.loadFromXML(Xml)method, passing it the node XML. If the class is annotated with anXmlRootElement, it will use JAXB to unmarshall it to an object.Performs XML validation if the target object has an associated schema.
- Type Parameters:
T- the type of the return value- Returns:
- a new object.
- Throws:
XmlValidationException- if the XML has validation errorsXmlException- if something prevented object creation
-
toObject
public <T> T toObject(T defaultObject) Creates a new instance of the class represented by the "class" attribute on the given node. The class must have an empty constructor. If the class is an instance of
XmlConfigurable, the object created will be automatically populated by invoking theXmlConfigurable.loadFromXML(Xml)method, passing it the node XML. If the class is annotated with anXmlRootElement, it will use JAXB to unmarshall it to an object.Performs XML validation if the target object has an associated schema.
- Type Parameters:
T- the type of the return value- Parameters:
defaultObject- if returned object is null or undefined, returns this default object.- Returns:
- a new object.
- Throws:
XmlException- if something prevented object creation
-
toObjectImpl
Creates a new instance of the class represented by the "class" attribute on this XML root node. The class must have an empty constructor. If the class is an instance of
XmlConfigurable, the object created will be automatically populated by invoking theXmlConfigurable.loadFromXML(Xml)method, passing it the node XML. If the class is annotated with anXmlRootElement, it will use JAXB to unmarshall it to an object.Other than making sure the class is a subtype of the specified super class, the main difference between method this and
toObject()is the support for partial class names. That is, this method will scan the current class loader for a class with its name ending with the value of the "class" attribute. If more than one is found, anXmlExceptionwill be thrown. If you are expecting fully qualified class names, use thetoObject()method, which is faster.- Type Parameters:
T- the type of the return value- Parameters:
type- the expected class (sub)type to return- Returns:
- a new object or
null. - Throws:
XmlValidationException- if the XML has validation errorsXmlException- if something prevented object creation
-
toObjectImpl
Creates a new instance of the class represented by the "class" attribute on the given node. The class must have an empty constructor. If the class is an instance of
XmlConfigurable, the object created will be automatically populated by invoking theXmlConfigurable.loadFromXML(Xml)method, passing it the node XML. If the class is annotated with anXmlRootElement, it will use JAXB to unmarshall it to an object.Other than making sure the class is a subtype of the specified super class, the main difference between method this and
toObject(Object)is the support for partial class names. That is, this method will scan the current class loader for a class with its name ending with the value of the "class" attribute. If more than one is found, anXmlExceptionwill be thrown. If you are expecting fully qualified class names, use thetoObject(Object)method, which is faster.- Type Parameters:
T- the type of the return value- Parameters:
type- the expected class (sub)type to returndefaultObject- if returned object is null or undefined, returns this default object.- Returns:
- a new object if not
null, else the default object. - Throws:
XmlException- if something prevented object creation
-
getObject
Creates a new instance of the class represented by the "class" attribute on the node matching the expression. The class must have an empty constructor. If the class is an instance of
XmlConfigurable, the object created will be automatically populated by invoking theXmlConfigurable.loadFromXML(Xml)method, passing it the node XML.This method should throw a
XmlExceptionupon error. Use a method with a default value argument to avoid throwing exceptions.- Type Parameters:
T- the type of the return value- Parameters:
xpathExpression- xpath expression- Returns:
- a new object.
-
getObject
Creates a new instance of the class represented by the "class" attribute on the node matching the expression. The class must have an empty constructor. If the class is an instance of
XmlConfigurable, the object created will be automatically populated by invoking theXmlConfigurable.loadFromXML(Xml)method, passing it the node XML.This method should not throw exception upon errors, but will return the default value instead (even if null). Use a method without a default value argument to get exceptions on errors.
- Type Parameters:
T- the type of the return value- Parameters:
xpathExpression- xpath expressiondefaultObject- if returned object is null or undefined, returns this default object.- Returns:
- a new object.
-
getObjectList
Creates an instance list from classes represented by the "class" attribute on the nodes matching the expression. The classes must have an empty constructor. If a class is an instance of
XmlConfigurable, the object created will be automatically populated by invoking theXmlConfigurable.loadFromXML(Xml)method, passing it the node XML.This method should not throw exception upon errors, but will return the default value instead (even if null). Use a method without a default value argument to get exceptions on errors.
- Type Parameters:
T- the type of the return value- Parameters:
xpathExpression- xpath expressiondefaultObjects- if returned list is empty, returns this default list.- Returns:
- a new object.
- Throws:
XmlException- if instance cannot be created/populated
-
getObjectList
Creates an instance list from classes represented by the "class" attribute on the nodes matching the expression. The classes must have an empty constructor. If a class is an instance of
XmlConfigurable, the object created will be automatically populated by invoking theXmlConfigurable.loadFromXML(Xml)method, passing it the node XML.This method should throw a
XmlExceptionupon error. Use a method with a default value argument to avoid throwing exceptions.- Type Parameters:
T- the type of the return value- Parameters:
xpathExpression- xpath expression- Returns:
- a new object.
- Throws:
XmlException- if instance cannot be created/populated
-
getObjectImpl
Creates a new instance of the class represented by the "class" attribute on the node matching the expression. The class must have an empty constructor. If the class is an instance of
XmlConfigurable, the object created will be automatically populated by invoking theXmlConfigurable.loadFromXML(Xml)method, passing it the node XML.This method should throw a
XmlExceptionupon error. Use a method with a default value argument to avoid throwing exceptions.Other than making sure the class is a subtype of the specified super class, the main difference between method this and
getObject(String)is the support for partial class names. That is, this method will scan the current class loader for a class with its name ending with the value of the "class" attribute. If more than one is found, anXmlExceptionwill be thrown. If you are expecting fully qualified class names, use thegetObject(String)method, which is faster.- Type Parameters:
T- the type of the return value- Parameters:
type- the expected class (sub)type to returnxpathExpression- xpath expression- Returns:
- a new object.
-
getObjectImpl
Creates a new instance of the class represented by the "class" attribute on the node matching the expression. The class must have an empty constructor. If the class is an instance of
XmlConfigurable, the object created will be automatically populated by invoking theXmlConfigurable.loadFromXML(Xml)method, passing it the node XML.This method should not throw exception upon errors, but will return the default value instead (even if null). Use a method without a default value argument to get exceptions on errors.
Other than making sure the class is a subtype of the specified super class, the main difference between method this and
getObject(String, Object)is the support for partial class names. That is, this method will scan the current class loader for a class with its name ending with the value of the "class" attribute. If more than one is found, anXmlExceptionwill be thrown. If you are expecting fully qualified class names, use thegetObject(String, Object)method, which is faster.- Type Parameters:
T- the type of the return value- Parameters:
type- the expected class (sub)type to returnxpathExpression- xpath expressiondefaultObject- if returned object is null or undefined, returns this default object.- Returns:
- a new object.
-
getObjectListImpl
Creates an instance list from classes represented by the "class" attribute on the nodes matching the expression. The classes must have an empty constructor. If a class is an instance of
XmlConfigurable, the object created will be automatically populated by invoking theXmlConfigurable.loadFromXML(Xml)method, passing it the node XML.This method should not throw exception upon errors, but will return the default value instead (even if null). Use a method without a default value argument to get exceptions on errors.
Other than making sure the class is a subtype of the specified super class, the main difference between method this and
getObjectList(String, List)is the support for partial class names. That is, this method will scan the current class loader for a class with its name ending with the value of the "class" attribute. If more than one is found, anXmlExceptionwill be thrown. If you are expecting fully qualified class names, use thegetObjectList(String, List)method, which is faster.- Type Parameters:
T- the type of the return value- Parameters:
type- the expected class (sub)type to returnxpathExpression- xpath expressiondefaultObjects- if returned list is empty, returns this default list.- Returns:
- a new object.
- Throws:
XmlException- if instance cannot be created/populated
-
getObjectListImpl
Creates an instance list from classes represented by the "class" attribute on the nodes matching the expression. The classes must have an empty constructor. If a class is an instance of
XmlConfigurable, the object created will be automatically populated by invoking theXmlConfigurable.loadFromXML(Xml)method, passing it the node XML.This method should throw a
XmlExceptionupon error. Use a method with a default value argument to avoid throwing exceptions.Other than making sure the class is a subtype of the specified super class, the main difference between method this and
getObjectList(String)is the support for partial class names. That is, this method will scan the current class loader for a class with its name ending with the value of the "class" attribute. If more than one is found, anXmlExceptionwill be thrown. If you are expecting fully qualified class names, use thegetObjectList(String)method, which is faster.- Type Parameters:
T- the type of the return value- Parameters:
type- the expected class (sub)type to returnxpathExpression- xpath expression- Returns:
- a new object.
- Throws:
XmlException- if instance cannot be created/populated
-
getDelimitedList
Gets a list of the given type after splitting the matching node value(s) on commas (CSV). Values are trimmed and blank entries removed before attempting to convert them to given type. Commas can have any spaces before or after.- Type Parameters:
T- returned list type- Parameters:
xpathExpression- XPath expression to the node value(s) to splittype- target list type- Returns:
- list of given type, never
null
-
getDelimitedList
Gets a list of given type after splitting the matching node value(s) on commas (CSV). Values are trimmed and blank entries removed before attempting to convert them to given type. Commas can have any spaces before or after.- Type Parameters:
T- returned list type- Parameters:
xpathExpression- XPath expression to the node value(s) to splittype- target list typedefaultValues- default values if the split returnsnullor an empty list- Returns:
- list of strings
-
getDelimitedList
Gets a list of given type after splitting the matching node value(s) with the given delimiter regular expression. Values are trimmed and blank entries removed before attempting to convert them to given type.- Type Parameters:
T- returned list type- Parameters:
xpathExpression- XPath expression to the node value(s) to splittype- target list typedelimRegex- regular expression matching split delimiter- Returns:
- list of strings, never
null
-
getDelimitedList
public <T> List<T> getDelimitedList(String xpathExpression, Class<T> type, String delimRegex, List<? extends T> defaultValues) Gets a list of given type after splitting the matching node value(s) with the given delimiter regular expression. Values are trimmed and blank entries removed before attempting to convert them to given type.- Type Parameters:
T- returned list type- Parameters:
xpathExpression- XPath expression to the node value(s) to splittype- target list typedelimRegex- regular expression matching split delimiterdefaultValues- default values if the split returnsnullor an empty list- Returns:
- list of strings
-
getXML
Gets the xml subset matching the xpath expression.- Parameters:
xpathExpression- expression to match- Returns:
- XML or
nullis xpath has no match
-
getXMLList
Gets the XML subsets matching the xpath expression.- Parameters:
xpathExpression- expression to match- Returns:
- XML list, never
null
-
getNode
-
getNode
-
toNode
-
getString
-
getString
-
getStringList
Gets the matching list of elements/attributes as strings.- Parameters:
xpathExpression- XPath expression to the node values- Returns:
- list of strings, never
null
-
getStringList
Gets the matching list of elements/attributes as strings.- Parameters:
xpathExpression- XPath expression to the node valuesdefaultValues- default values if the expression does not match anything.- Returns:
- list of strings
-
getDelimitedStringList
Gets a list of strings after splitting the matching node value(s) on commas (CSV). Values are trimmed and blank entries removed. Commas can have any spaces before or after.- Parameters:
xpathExpression- XPath expression to the node value(s) to split- Returns:
- list of strings, never
null
-
getDelimitedStringList
Gets a list of strings after splitting the matching node value(s) on commas (CSV). Values are trimmed and blank entries removed. Commas can have any spaces before or after.- Parameters:
xpathExpression- XPath expression to the node value(s) to splitdefaultValues- default values if the split returnsnullor an empty list- Returns:
- list of strings
-
getDelimitedStringList
Gets a list of strings after splitting the matching node value(s) with the given delimiter regular expression. Values are trimmed before being split and blank entries removed.- Parameters:
xpathExpression- XPath expression to the node value(s) to splitdelimRegex- regular expression matching split delimiter- Returns:
- list of strings, never
null
-
getDelimitedStringList
public List<String> getDelimitedStringList(String xpathExpression, String delimRegex, List<String> defaultValues) Gets a list of strings after splitting the matching node value(s) with the given delimiter regular expression. Values are trimmed and blank entries removed.- Parameters:
xpathExpression- XPath expression to the node value(s) to splitdelimRegex- regular expression matching split delimiterdefaultValues- default values if the split returnsnullor an empty list- Returns:
- list of strings
-
getEnum
Gets an Enum constant matching one of the constants in the provided Enum class, ignoring case.- Type Parameters:
E- enum type- Parameters:
xpathExpression- XPath expression to the enum value.enumClass- target enum class- Returns:
- an enum value or
nullif no values are matching.
-
getEnum
public final <E extends Enum<E>> E getEnum(String xpathExpression, Class<E> enumClass, E defaultValue) Gets an Enum constant matching one of the constants in the provided Enum class, ignoring case.- Type Parameters:
E- enum type- Parameters:
xpathExpression- XPath expression to the enum value.enumClass- target enum classdefaultValue- defaultValue- Returns:
- an enum value or default value if no values are matching.
-
getEnumList
public <E extends Enum<E>> List<E> getEnumList(String xpathExpression, Class<E> enumClass, List<E> defaultValues) Gets a list of enum constants. Values are trimmed and blank entries removed before attempting to convert them to the given enum type.- Type Parameters:
E- enum type- Parameters:
xpathExpression- XPath expressionenumClass- target enum classdefaultValues- default values- Returns:
- list of enums
-
getDelimitedEnumList
public <E extends Enum<E>> List<E> getDelimitedEnumList(String xpathExpression, Class<E> enumClass, List<E> defaultValues) Gets a list of enum constants after splitting the matching node value(s) on commas (CSV). Values are trimmed and blank entries removed before attempting to convert them to the given enum type.- Type Parameters:
E- enum type- Parameters:
xpathExpression- XPath expression to the node value(s) to splitenumClass- target enum classdefaultValues- default values if the split returnsnullor an empty list- Returns:
- list of enums
-
getDelimitedEnumList
public <E extends Enum<E>> List<E> getDelimitedEnumList(String xpathExpression, Class<E> enumClass, String delimRegex, List<E> defaultValues) Gets a list of enum constants after splitting the matching node value(s) with the given delimiter regular expression. Values are trimmed and blank entries removed before attempting to convert them to given enum type.- Type Parameters:
E- enum type- Parameters:
xpathExpression- XPath expression to the node value(s) to splitenumClass- target enum classdelimRegex- regular expression matching split delimiterdefaultValues- default values if the split returnsnullor an empty list- Returns:
- list of enums
-
getPath
Gets a path, assuming the node value is a file system path.- Parameters:
xpathExpression- XPath expression to the node containing the path- Returns:
- a path
-
getPath
Gets a path, assuming the node value is a file system path.- Parameters:
xpathExpression- XPath expression to the node containing the pathdefaultValue- default path being returned if no path has been defined for the given expression.- Returns:
- a path
-
getPathList
Gets values as a list of paths.- Parameters:
xpathExpression- XPath expression- Returns:
- the values
-
getPathList
Gets values as a list of paths.- Parameters:
xpathExpression- XPath expressiondefaultValue- default value- Returns:
- the values
-
getFile
Gets a file, assuming the node value is a file system path.- Parameters:
xpathExpression- XPath expression to the node containing the path- Returns:
- a File
-
getFile
Gets a file, assuming the node value is a file system path.- Parameters:
xpathExpression- XPath expression to the node containing the pathdefaultValue- default file being returned if no file has been defined for the given expression.- Returns:
- a File
-
getFileList
Gets values as a list of files.- Parameters:
xpathExpression- XPath expression- Returns:
- the values
-
getFileList
Gets values as a list of files.- Parameters:
xpathExpression- XPath expressiondefaultValue- default value- Returns:
- the values
-
getURL
-
getURL
-
getURLList
-
getURLList
-
getInteger
-
getInteger
-
getLong
-
getLong
-
getFloat
-
getFloat
-
getDimension
-
getDimension
-
getDouble
-
getDouble
-
getBoolean
-
getBoolean
-
getLocale
-
getLocale
-
getCharset
-
getCharset
-
getDataSize
Gets the size of a data expression, in bytes (e.g., 2KB, 1GiB, 3 megabytes, etc). Without a unit specified, the value is assumed to represent bytes.- Parameters:
xpathExpression- xpath to the element/attribute with the size- Returns:
- size in bytes
- Since:
- 2.0.0
-
getDataSize
Gets the size of a data expression, in bytes (e.g., 2KB, 1GiB, 3 megabytes, etc). Without a unit specified, the value is assumed to represent bytes.- Parameters:
xpathExpression- xpath to the element/attribute with the sizedefaultValue- default value- Returns:
- size in bytes or default value if size is
null - Since:
- 2.0.0
-
getDataSize
Gets the size of a data expression, in the specified target unit (e.g., 2KB, 1GiB, 3 megabytes, etc). Without a unit specified in the value, the value is assumed to represent bytes.- Parameters:
xpathExpression- xpath to the element/attribute with the sizetargetUnit- the unit to convert the value intodefaultValue- default value- Returns:
- size in bytes or default value if size is
null - Since:
- 2.0.0
-
getDurationMillis
Gets a duration in milliseconds which can exists as a numerical value or a textual representation of a duration as perDurationParser. If the key value is found but there are parsing errors, aDurationParserExceptionwill be thrown.- Parameters:
xpathExpression- xpath to the element/attribute containing the duration- Returns:
- duration in milliseconds
-
getDurationMillis
Gets a duration in milliseconds which can exists as a numerical value or a textual representation of a duration as perDurationParser. If the key value is found but there are parsing errors, aDurationParserExceptionwill be thrown.- Parameters:
xpathExpression- xpath to the element/attribute containing the durationdefaultValue- default duration- Returns:
- duration in milliseconds
-
getDuration
Gets a duration which can exists as a numerical value or a textual representation of a duration as perDurationParser. If the duration does not exists for the given key or is blank,nullis returned. If the key value is found but there are parsing errors, aDurationParserExceptionwill be thrown.- Parameters:
xpathExpression- xpath to the element/attribute containing the duration- Returns:
- duration
-
getDuration
Gets a duration which can exists as a numerical value or a textual representation of a duration as perDurationParser. If the duration does not exists for the given key or is blank, the default value is returned. If the key value is found but there are parsing errors, aDurationParserExceptionwill be thrown.- Parameters:
xpathExpression- xpath to the element/attribute containing the durationdefaultValue- default duration- Returns:
- duration
-
getPattern
Gets a regular expression pattern.- Parameters:
xpathExpression- xpath to the element/attribute with the pattern- Returns:
- pattern
- Since:
- 3.0.0
-
getPattern
Gets a regular expression pattern.- Parameters:
xpathExpression- xpath to the element/attribute with the patterndefaultValue- default value- Returns:
- pattern
- Since:
- 3.0.0
-
validate
public void validate()Validates this XML against an XSD schema attached to the class represented in this XML root tag "class" attribute.
Error handling
The expected behavior when encountering validation errors is tied to the registered
ErrorHandler. When no error handler is specified, the default isErrorHandlerFailer(which throwsXmlValidationException). Error handlers can be specified when using the builder obtained with one of theXML.of(...)) methods.The XSD schema used for validation is expected to be found at the same classpath location and have the same name as the object class, but with the ".xsd" extension.
This method is the same as invoking
validate(getClass("@class"))- See Also:
-
validate
Validates this XML against an XSD schema attached to the class represented in this XML root tag "class" attribute.
Error handling
The expected behavior when encountering validation errors is tied to the registered
ErrorHandler. When no error handler is specified, the default isErrorHandlerFailer(which throwsXmlValidationException). Error handlers can be specified when using the builder obtained with one of theXML.of(...)) methods..The XSD schema used for validation is expected to be found at the same classpath location and have the same name as the object class, but with the ".xsd" extension.
This method is the same as invoking
validate(obj.getClass())- Parameters:
obj- the object used to locate the XML schema used for validation- See Also:
-
validate
Validates this XML against an XSD schema attached to the class represented in this XML root tag "class" attribute.
Error handling
The expected behavior when encountering validation errors is tied to the registered
ErrorHandler. When no error handler is specified, the default isErrorHandlerFailer(which throwsXmlValidationException). Error handlers can be specified when using the builder obtained with one of theXML.of(...)) methods..The XSD schema used for validation is expected to be found at the same classpath location and have the same name as the object class, but with the ".xsd" extension.
- Parameters:
clazz- the class with XSD schema attached, used for validation- See Also:
-
isEnabled
public boolean isEnabled() -
isDisabled
public boolean isDisabled() -
isElementPresent
Gets whether the given expression matches an existing element. A blank expression always returnsfalse.- Parameters:
xpathExpression- expression- Returns:
trueif the expression matches an element- Since:
- 3.0.0
-
ifXML
If the given expression matches an element, consume that element.- Parameters:
xpathExpression- expressionthen- XML consumer
-
toReader
Creates a newReaderfrom aNode. Do not forget to close the reader instance when you are done with it.- Returns:
- reader
- Throws:
XmlException- cannot read configuration
-
equals
-
hashCode
public int hashCode() -
toString
Gets a string representation of this XML.- Overrides:
toStringin classObject- Returns:
- XML string
- Throws:
XmlException- cannot read configuration
-
toString
Gets a string representation of this XML.- Parameters:
indent- whether to indent the XML- Returns:
- XML string
- Throws:
XmlException- cannot read configuration
-
forEach
If the given expression matches one or more elements, consume those element one by one.- Parameters:
xpathExpression- expressionaction- The action to be performed for each element
-
assertWriteRead
Convenience class for testing that an object annotated with JAXBXmlRootElementor implementingXmlConfigurable(or both) can be written, and read back into an new instance that is equal as perequals(Object).- Parameters:
object- the instance object to test if it written/read properlyelementName- the tag name of the root element being written- Throws:
XmlException- Cannot write/read configuration or the read object is not equal to the original one that was written.
-
contains
-
newXPath
Deprecated.UseXpathUtil.newXPath()insteadGets a new XPath instance from the default object model.- Returns:
- new XPath instance
-
newXPathExpression
Deprecated.UseXpathUtil.newXPathExpression(String)insteadGets a new compiledXPathExpressionfrom the given string.- Parameters:
expression- the XPath string- Returns:
- compiled XPath expression
-
get
Gets the matching element/attribute, converted from string to the given type.- Type Parameters:
T- target type- Parameters:
xpathExpression- XPath expression to the node valuetype- target class type of returned value- Returns:
- object of given type
-
get
Gets the matching element/attribute, converted from string to the given type.- Type Parameters:
T- target type- Parameters:
xpathExpression- XPath expression to the node valuetype- target class type of returned valuedefaultValue- default value if the expression returnsnull- Returns:
- object of given type
-
getList
Gets the matching list of elements/attributes, converted from string to the given type.- Type Parameters:
T- returned list type- Parameters:
xpathExpression- XPath expression to the node valuestype- target class type of returned list- Returns:
- list of given type, never
null
-
getList
public <T> List<? extends T> getList(String xpathExpression, Class<T> type, List<? extends T> defaultValues) Gets the matching list of elements/attributes, converted from string to the given type.- Type Parameters:
T- returned list type- Parameters:
xpathExpression- XPath expression to the node valuestype- target class type of returned listdefaultValues- default values if the expression returnsnullor an empty list- Returns:
- list of given type
-
getStringMap
Gets the matching map of elements/attributes as strings.- Parameters:
xpathList- XPath expression to the node list representing the mapxpathKey- XPath expression to a node keyxpathValue- XPath expression to a node value- Returns:
- map of strings, never
null
-
getStringMap
public Map<String,String> getStringMap(String xpathList, String xpathKey, String xpathValue, Map<String, String> defaultValues) Gets the matching map of elements/attributes as strings.- Parameters:
xpathList- XPath expression to the node list representing the mapxpathKey- XPath expression to a node keyxpathValue- XPath expression to a node valuedefaultValues- default values if the expressions returnnullor an empty map- Returns:
- map of strings, never
nullunless default value is returned and isnull
-
getName
-
computeElementIfAbsent
Computes and adds the element returned by the provided function if an element with the same name is not already present, else, return the existing one. Passing anullfunction ornullvalue returned by the function when there are no existing element will add a new empty element.- Parameters:
tagName- element namefunction- taking the new element name and returning the element- Returns:
- XML of the added element, or the already existing element
- Since:
- 3.0.0
-
addElement
Adds an empty child element to this XML root element.- Parameters:
tagName- element name- Returns:
- XML of the added element
-
addElement
Adds a child element to this XML root element. If the element value is blank, and empty element is created. Otherwise, the value is handled as
of(String, Object)- Parameters:
tagName- element namevalue- element value- Returns:
- XML of the added element
-
addElementList
Adds a list of values to the current XML and return the added list. There will be one element added for each entry of the supplied list, all with the tag name supplied.- Parameters:
tagName- the tag name for each values addedvalues- values to add- Returns:
- the added list as a list of XML instances
-
addElementList
Adds a list of values under a new parent tag name to the current XML and return the added list. There will be one element added for each entry of the supplied list, all with the tag name supplied, all grouped under the parent tag supplied.- Parameters:
parentTagName- the name of the new parent tag that will hold all added values.tagName- the tag name for each values addedvalues- values to add- Returns:
- the XML for the parent tag
-
addDelimitedElementList
Adds a list of values as a new element after joining them with a comma (CSV). Values are trimmed and blank entries removed. Values can be of any types, as they converted to String by invoking their "toString()" method.- Parameters:
name- attribute namevalues- attribute values- Returns:
- the newly added element
-
addDelimitedElementList
Adds a list of values as a new element after joining them with the given delimiter. Values are trimmed and blank entries removed. Values can be of any types, as they converted to String by invoking their "toString()" method.- Parameters:
name- attribute namedelim- delimitervalues- attribute values- Returns:
- the newly added element
-
addElementMap
Adds a
Mapas a series of elements without a parent element wrapping that group. Map keys are defined as element attributes and the map value is the element content. The structure can be visualized like this:<tagName attributeName="(key)">(value)</tagName> <tagName attributeName="(key)">(value)</tagName> ...
Map keys are assumed to be strings or single objects with supported conversion to string (see
GenericConverter). Map values can be single values or multi-values. Arrays or collections will have their values be treated as individual elements with the same key name. In any case, single or multiple values are otherwise converted to strings just like keys.- Parameters:
tagName- name of tags for each map entriesattributeName- name of the tag attribute holding the map entry keymap- map to add- Returns:
- XML of parent tag, with nested element for each map entries, or
nullif map isnull.
-
addElementMap
Adds a
Mapas a series of elements with a parent element wrapping that group. Map keys are defined as element attributes and the map value is the element content. The structure can be visualized like this:<parentTagName> <tagName attributeName="(key)">(value)</tagName> <tagName attributeName="(key)">(value)</tagName> ... </parentTagName>
Map keys are assumed to be strings or single objects with supported conversion to string (see
GenericConverter). Map values can be single values or multi-values. Arrays or collections will have their values be treated as individual elements with the same key name. In any case, single or multiple values are otherwise converted to strings just like keys.- Parameters:
parentTagName- required name of map elements wrapper tagtagName- name of tags for each map entriesattributeName- name of the tag attribute holding the map entry keymap- map to add- Returns:
- XML of parent tag, with nested element for each map entries, or
nullif map isnull.
-
removeElement
Removes an element from this XML.- Parameters:
tagName- element name- Returns:
- XML of the removed element
-
remove
Removes itself from its XML parent (if any).- Returns:
- a new instance of this removed XML or this instance if it is not attached to any parent
-
insertBefore
Inserts a new XML node before this one, as a sibling of a shared parent. If there is no parent to this XML, the new XML is not inserted.- Parameters:
newXML- the XML to insert- Returns:
- a new instance of the inserted XML, or the inserted node if this node is not attached to any parent.
-
insertAfter
Inserts a new XML node after this one, as a sibling of a shared parent. If there is no parent to this XML, the new XML is not inserted.- Parameters:
newXML- the XML to insert- Returns:
- a new instance of the inserted XML, or the inserted node if this node is not attached to any parent.
-
setAttribute
Sets an attribute on this XML element, converting the supplied object to a string (enums are also converted to lowercase). Anullvalue is equivalent to not adding or removing that attribute.- Parameters:
name- attribute namevalue- attribute value- Returns:
- this element
-
setAttributes
Sets attributes on this XML element.- Parameters:
attribs- attributes- Returns:
- this element
-
setDelimitedAttributeList
Sets a list of values as an attribute after joining them with a comma (CSV). Values are trimmed and blank entries removed. Values can be of any types, as they converted to String by invoking their "toString()" method.- Parameters:
name- attribute namevalues- attribute values- Returns:
- this element
-
setDelimitedAttributeList
Sets a list of values as an attribute after joining them with the given delimiter. Values are trimmed and blank entries removed. Values can be of any types, as they converted to String by invoking their "toString()" method.- Parameters:
name- attribute namedelim- delimitervalues- attribute values- Returns:
- this element
-
removeAttribute
Removes an attribute on this XML element.- Parameters:
name- attribute name- Returns:
- this element
-
setTextContent
Sets the direct text content of an XML element. To replace all child nodes with text, usexml.getNode().setTextContent("my content"). Settingnullcontent is effectively the same as invokingremoveTextContent().- Parameters:
textContent- text content- Returns:
- this element
-
getTextContent
Gets this XML direct text content, if any, joining multiple text nodes by a space separator. To get all text content, including text content of child elements, usexml.getNode().getTextContent().- Returns:
- this XML text, or
nullif no text - Since:
- 3.0.0
-
removeTextContent
Removes this XML direct text content, without impact on attributes and child elements and their content.- Returns:
- this XML without text content
-
addXML
-
addXML
-
addXML
-
getXMLWriter
-
getXMLStreamWriter
Deprecated. -
write
-
write
-
write
-
write
-
unwrap
Unwraps this XML by removing the root tag and keeping its child element (and its nested element). If there are no child (i.e., nothing to unwrap), invoking this method has no effect. If there are more than one child element, this method throws anXmlException.- Returns:
- this XML, unwrapped
-
rename
Rename this XML (element tag name).- Parameters:
newName- new name for this XML- Returns:
- this XML, renamed
-
wrap
Wraps this XML by adding a parent element around it.- Parameters:
parentName- name of wrapping element- Returns:
- this XML, wrapped
-
clear
Clears this XML by removing all its attributes and elements (i.e., making it an empty tag).- Returns:
- this cleared XML
-
isEmpty
public boolean isEmpty()Gets whether this XML is empty. An XML is considered empty if all ofhasAttributes(),hasChildElements(), andhasTextContent()returnfalse.- Returns:
trueif empty- Since:
- 3.0.0
-
hasChildElements
public boolean hasChildElements()Gets whether this XML element has any child elements.- Returns:
trueif this element has at least one child element- Since:
- 3.0.0
-
hasAttributes
public boolean hasAttributes()Gets whether this XML element has any attributes.- Returns:
trueif this element has at least one attribute- Since:
- 3.0.0
-
hasTextContent
public boolean hasTextContent()Gets whether this XML has any text content.- Returns:
trueif non-nulland non-empty.- Since:
- 3.0.0
-
replace
Replaces the current XML with the provided one.- Parameters:
replacement- replacing XML- Returns:
- this XML, replaced
-
getClass
-
getClass
-
getClassList
Gets values as a list of files.- Type Parameters:
T- returned list type- Parameters:
xpathExpression- XPath expression- Returns:
- the values
-
getClassList
public final <T> List<Class<? extends T>> getClassList(String xpathExpression, List<Class<? extends T>> defaultValue) Gets values as a list of files.- Type Parameters:
T- returned list type- Parameters:
xpathExpression- XPath expressiondefaultValue- default value- Returns:
- the values
-
parseXML
-
parseXML
-
parseXMLList
-
parseXMLList
-
parseXMLMap
-
parseXMLMap
-
checkDeprecated
Checks whether a deprecated configuration entry was specified and log a warning or throw anXmlException.- Parameters:
deprecatedXPath- xpath to the invalid entryreplacement- new xpath or instructions to replacethrowException-trueto throw exception, else log a warning
-
checkDeprecated
Checks whether a deprecated configuration entry (without replacement) was specified and log a warning or throw anXmlException.- Parameters:
deprecatedXPath- xpath to the invalid entrythrowException-trueto throw exception, else log a warning
-
getErrorHandler
-
getDocumentBuilderFactory
-
isXMLConfigurable
-
isJAXB
-
iterator
-
stream
Returns aStreamofXmlCursorfrom this XML, in sequential order. Invoking a "read" methods onXmlCursorwhich reads child elements will result in the stream skipping those already read elements.- Returns:
- XML cursor stream
-
iterator
Returns an
IteratorofXmlCursorfrom the supplied XML object, in sequential order. Invoking a "read" methods onXmlCursorwhich reads child elements will result in the iterator skipping those already read elements.The object argument type must be one of the following:
- Parameters:
obj- the XML to iterate over- Returns:
- XML cursor iterator
-
stream
Returns a
StreamofXmlCursorfrom the supplied XML object, in sequential order. Invoking a "read" methods onXmlCursorwhich reads child elements will result in the stream skipping those already read elements.The object argument type must be one of the following:
- Parameters:
obj- the XML to stream- Returns:
- XML cursor stream
-
join
Deprecated.Will be removed or visibility reduced in a future release.Joins multiple values using the supplied delimiter or a comma if the delimiter isnull.- Parameters:
delim- delimitervalues- the values to join- Returns:
- joined values, as a string
-